Learning Resources
 

Handling and raising Exceptions


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.

#!/usr/bin/python
# Filename: try_except.py
 
try:
    text = input('Enter something --> ')
except EOFError:
    print('Why did you do an EOF on me?')
except KeyboardInterrupt:
    print('You cancelled the operation.')
else:
    print('You entered {0}'.format(text))

Output:

   $ python try_except.py
   Enter something -->     # Press ctrl-d
   Why did you do an EOF on me?
   
   $ python try_except.py
   Enter something -->     # Press ctrl-c
   You cancelled the operation.
   
   $ python try_except.py
   Enter something --> no exceptions
   You entered no exceptions

How It Works:

We put all the statements that might raise exceptions/errors inside the try block and then put handlers for the appropriate errors/exceptions in the except clause/block. The except clause can handle 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 called which just stops the execution of the program and prints an error message. We have already seen this in action above.

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

In the next example, we will also see how to get the exception object so that we can retrieve additional information.

Raising Exceptions

You can raise exceptions using the raise statement by providing the name of the error/exception and the exception 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.

#!/usr/bin/python
# Filename: raising.py
 
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 something --> ')
    if len(text) < 3:
        raise ShortInputException(len(text), 3)
    # Other work can continue as usual here
except EOFError:
    print('Why did you do an EOF on me?')
except ShortInputException as ex:
    print('ShortInputException: The input was {0} long, expected at least {1}'\
          .format(ex.length, ex.atleast))
else:
    print('No exception was raised.')

Output:

   $ python raising.py
   Enter something --> a
   ShortInputException: The input was 1 long, expected at least 3
   
   $ python raising.py
   Enter something --> abc
   No exception was raised.

How It Works:

Here, we are creating our 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 the minimum length that the program was expecting.

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

-Swaroopch