Python en:Exceptions

Introduction
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 accidentally deleted it when the program was running? Such situations are handled using exceptions.

Similarly, what if your program had 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 if we misspelt print as Print? Note the capitalization. In this case, Python raises a syntax error.

>>> Print('Hello World') Traceback (most recent call last): File "", line 1, in        Print('Hello World') NameError: name 'Print' is not defined >>> print('Hello World') Hello World

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 read input from the user. Press ctrl-d and see what happens.

>>> s = input('Enter something --> ') Enter something --> Traceback (most recent call last): File "", line 1, in        s = input('Enter something --> ') EOFError: EOF when reading a line

Python raises an error called EOFError which basically means it found an end of file symbol (which is represented by ctrl-d) when it did not expect to see it.

Handling Exceptions
We can handle exceptions using the try..except</tt> statement. We basically put our usual statements within the try-block and put all our error handlers in the except-block.

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</tt> block and then put handlers for the appropriate errors/exceptions in the except</tt> clause/block. The except</tt> 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</tt> clause associated with every try</tt> 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</tt> clause associated with a try..except</tt> block. The else</tt> 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</tt> 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 arise should be class which directly or indirectly must be a derived class of the Exception</tt> class.

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</tt>. It has two fields - length</tt> which is the length of the given input, and atleast</tt> which is the minimum length that the program was expecting.

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

Try .. Finally
Suppose you are reading a file in your program. How do you ensure that the file object is closed properly whether or not an exception was raised? This can be done using the <tt>finally</tt> block. Note that you can use an <tt>except</tt> clause along with a <tt>finally</tt> block for the same corresponding <tt>try</tt> block. You will have to embed one within another if you want to use both.

Output:

$ python finally.py   Programming is fun When the work is done if you wanna make your work also fun: !! You cancelled the reading from the file. (Cleaning up: Closed the file)

How It Works:

We do the usual file-reading stuff, but we have arbitrarily introduced sleeping for 2 seconds after printing each line using the <tt>time.sleep</tt> function so that the program runs slowly (Python is very fast by nature). When the program is still running, press <tt>ctrl-c</tt> to interrupt/cancel the program.

Observe that the <tt>KeyboardInterrupt</tt> exception is thrown and the program quits. However, before the program exits, the finally clause is executed and the file object is always closed.

The with statement
Acquiring a resource in the <tt>try</tt> block and subsequently releasing the resource in the <tt>finally</tt> block is a common pattern. Hence, there is also a <tt>with</tt> statement that enables this to be done in a clean manner:

How It Works:

The output should be same as the previous example. The difference here is that we are using the <tt>open</tt> function with the <tt>with</tt> statement - we leave the closing of the file to be done automatically by <tt>with open</tt>.

What happens behind the scenes is that there is a protocol used by the <tt>with</tt> statement. It fetches the object returned by the <tt>open</tt> statement, let's call it "thefile" in this case.

It always calls the <tt>thefile.__enter__</tt> function before starting the block of code under it and always calls <tt>thefile.__exit__</tt> after finishing the block of code.

So the code that we would have written in a <tt>finally</tt> block is should be taken care of automatically by the <tt>__exit__</tt> method. This is what helps us to avoid having to use explicit <tt>try..finally</tt> statements repeatedly.

More discussion on this topic is beyond scope of this book, so please refer PEP 343 for comprehensive explanation.

Summary
We have discussed the usage of the <tt>try..except</tt> and <tt>try..finally</tt> statements. We have seen how to create our own exception types and how to raise exceptions as well.

Next, we will explore the Python Standard Library.

Previous Next