Xtralien Scientific Python: Exceptions

 

Exceptions are used in Python to express when an error has occurred. Usually they will provide a detailed explanation of where the program stopped. Additionally the the exception may explain why the program has failed, although this is not always possible.

Creating exceptions

To create an exception you raise an Exception. To do this you use the raise keyword alongside the error that you want. To raise a generic exception you can use the Exception class. The Exception class is used as the root of all Exceptions, meaning that most exceptions ‘wrap’ the Exception class.

raise Exception("A generic Error")

In the above exception you can see that we have used the raise keyword to raise the exception Exception, with a message of "A generic Error". This message is provided to assist in debugging your program if it breaks. Because this happens as the program is running you can dynamically create this message using techniques like string formatting. An example of this can be seen below.

raise Exception("Error code: {}".format(404))

Handling Exceptions

Often you will want to ‘handle’ exceptions so that your script doesn’t break halfway through and ruin what you have prepared. To add in this error handling you need to make use of the try/except structure.

try:
    pass # Do something that might break here
except KeyError as e:
    print("Handled KeyError", e)
except IOError:
    print("Handled IOError")
except:
    print("Exception handled, resuming normal operation")
    
print("Normal operation")

The example above shows how you can handle exceptions in different ways. In the try section you should put your breaking code.

The first one of these is the except KeyError as e. This will check that the exception is a KeyError (the error for accessing a missing dictionary key), and then store the exception in e if it is.

The second handler is except IOError, which will check if the exception is an IOError (The error code for trying to access files that don’t exist). This one will not store the exception, but just stop it from propogating further. This is useful if you need to retry something.

Finally there is except by itself, which is shorthand for except Exception, due to Exception being the base exception class. This is the default for any exceptions that haven’t already been handled. Similar to the else in an if/else structure.

After any errors have been handled the program will continue normal execution. In this case, this means that Normal Operation will be printed to the console.

Note: When an exception occurs, any code in the same block after the exception will not execute.

Defining new exceptions

Defining new exceptions is simple, even without knowing how to define new classes.

class MyNewError(Exception):
    pass

The example above will define a new error MyNewError that is based on Exception. Because the definition consists of just the pass keyword no special behaviour will be implemented.

To raise this error we can use use the first example.

raise MyNewError("An error occurred")

To catch your exception, but no other exception we can also use code from above.

try:
    raise MyNewError("An error occurred")
except MyNewError:
    print("A MyNewError occurred")

The above example shows how you can define an error and handle instances of this error.