Lesson 7
Objects and Dictionaries
Chapter 7: Exception handling
After handling the exceptions
Sometimes we need to continue running some code, but only if no error occurred. For example, lines 3-5 run if there are no errors. And whether or not there was a ZeroDivisionError
, we will print "The end."
(line 9).
1 2 3 4 5 6 7 8 9 |
|
But I also mentioned earlier that PEP 8 actually recommends that you keep the code in a try
clause to the absolute minimum necessary. This avoids disguising a different error (perhaps a ZeroByDivisionError
might occur in a different line).
So how do we keep the try
block minimum, but at the same time execute some code only if there are no errors?
Easy! Use an else
clause. Anything inside else
will execute only if there were no errors while in the try
block.
1 2 3 4 5 6 7 8 9 10 11 |
|
Finally, you can also have code that must execute whether or not an exception occurred. Such codes can be put inside a finally
block.
1 2 3 4 5 6 7 8 9 10 11 |
|
How is it different from not using finally
? Well, the finally
block must run, whatever happens. For example, line 2 in the example below should raise a ValueError
but is not caught. If you run this code, Python will naturally report a ValueError
, but notice what gets printed before that? You guessed it - "The end."
.
1 2 3 4 5 6 |
|
The finally
clause is mainly useful for specifying some ‘cleanup’ code. For example, we might need to close a file properly, whether or not any error occurs while the file is still open.