Python 3x Pandas Django

Python Try...Except

Exceptions occur when certain exceptional situations occur in your program. For example, what if you are going to read a file and the file does not exist? Or what if you accidentlly deleted it when the program was running? Such situations are handled using exceptions

Similarly, what if your program has some invalid statements? This is handled by Python which raises its hands and tells you there is an error.

Errors

Consider a simple print function call. What is we misspelt print as Print? Note the capitalization.

In this case Python raises a syntax error.

Print("Hello World")

Output:

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
 in 
----> 1 Print("Hello World")

NameError: name 'Print' is not defined

Observe that a NameError is raised and also the location where the error was detected is printed. This is what an error handler for this error does.

Exceptions

We will try to divide '2' by '0' and see what happens

print(2/0)

Output:

---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
 in 
----> 1 2/0

ZeroDivisionError: division by zero

Python raised an error calls ZeroDivisionError which is basically means Python doesn't handle division by 0.

Handling Exceptions

We can handle exceptions using the try.. except statement. We basically put our usual statements within the try-block and put all our error handlers in the except-block.

try:
  Print("Hello World")
except NameError:
  print("Something went wrong.. Please check print statement")

Output:

Something went wrong.. Please check print statement

Let's check ZeroDivisionError exception

try:
  print(2/0)
except NameError:
  print("Something went wrong. Please check print statement.")
except ZeroDivisionError:
  print("Python doesn't handle division by 0. Please check.")
except:
  print("Somthing went wrong. Please check your program.")

Output:

Python doesn't handle division by 0. Please check.

How It Works

We put all the statements that might raise exceptions/error inside the try-block and then put handlers for the appropiate errors/exceptions in the except clause/block. The except clause can hadle a single specified error or exception, or a parenthesized list of errors/exceptions.

If no names of errors or exceptions are supplied, it will handle all errors and exceptions.

Note that there has to be at least one except clause associated with every try clause. Otherwise, what's the point of having a try-block?

If any error or exception is not handled, then the default python handler is call which just stops the exception of the program and prints an error message. We have already seen this in the beginning of this section

else: block

You can also have an else clause associated with a try..except block. The else clause is executed if no exception occurs

try:
  print("Hello World")
except NameError:
  print("Something went wrong.. Please check print statement")
else:
  print("You code ran successfully.")

Output:

Hello World
You code ran successfully.

finally: block

The finally block, if specified, will be executed regardless if the try block raises an error or not.

try:
  print(x)
except:
  print("Something went wrong")
finally:
  print("The 'try except' is finished")

Output:

Something went wrong
The 'try except' is finished

Finally can be useful to close objects and clean up resources:

try:
  f = open("sample_file.txt")
  f.write("Hello World")
except:
  print("Something went wrong when writing to the file")
finally:
  f.close()

Raising Exceptions(Custom Error)

You can raise exceptions using the raise statement by providing the name of the error/exception and the extension object that is to be thrown.

The error or exception that you can raise should be a class which directly or indirectly must be a derived class of the exception class.

class GreaterZero(Exception):
    """Base class for exceptions in this module."""
    pass

x = -1

try:
    if x < 0:
      raise GreaterZero
    else:
      print(x)
except GreaterZero:
    print("Sorry, x value should be greater than Zero")
except:
    print("Somthing went wrong!!!")

The raise keyword is used to raise an exception.

You can define what kind of error to raise, and the text to print to the user.

Raising Exceptions Example

class ShortInputException(Exception):
    "A user defined exception class."
    def __init__(self, length, atleast):
        Exception.__init__(self)
        self.length = length
        self.atleast = atleast


try:
    text = input("Enter Somthing -->")
    if len(text) < 3:
        raise ShortInputException(len(text), 3)
    # Other work can continue as usual here
except ShortInputException as ex:
    print("ShortInputException: The input was {0} long, excepted at least {1}"\
    .format(ex.length, ex.atleast))
else:
    print('No Exception was raised')

Output:

Enter Somthing -->a
ShortInputException: The input was 1 long, excepted at least 3

Enter Somthing -->abc
No Exception was raised

How It works - Here, we are creating own exception type. This new exception type is called ShortInputException. it has two fields - length which is the length of the given input, and atleast which is maximum length that the program was excepting.

In the except clause, we mention the class of error which will be stored as the varaible name to hold the corresponding error/exception object. This is analogous to parameters and aruguments in a function call. Within this particuler except clause, we use the length and atleast fields of the exception object to print an appropriate message to the user

Find the list of Built-in exceptions from python docs

If you have any doubts or queries related to this chapter, get them clarified from our Python Team experts on ibmmainframer Community!