It is also worth mentioning the optional else procedure, which is executed only when there is no exception in the related try , i.e.
- if an else procedure is present, it must follow except procedure
- there can be only one else procedure (or none)
Use the else proc. if you don’t want a certain piece of code to be contained in a try part. If you put all the code in a try procedure instead, the cause of the exception would be potentially more difficult to locate.
Another optional procedure is a finally proc., which executes whether or not there is an exception:
- if there is a finally proc. it must be placed after except and else (if present).
- there can be only one finally proc. (or none)
The finally block is mainly used for releasing access to external resources eg. databases.
Of course, we can also use the syntax in which the exception description is assigned to a variable and we can then display it in the handling procedure, e.g.
except NameError as e:
You can create a common handler for several exceptions by putting class names in a tuple, e.g.
except (ZeroDivisionError, NameError):
# Here we put the handler for these two exceptions
What you should pay attention to is that exceptions that are child classes in the hierarchy of exception classes are handled before the classes from which they inherit. The wrong order will result in the exception being handled by the more general procedure that came first, i.e.
print('It catches all exceptions!')
In the above example, NameError will be handled by the procedure in the first except block. Despite the NameError exception, the following message will be displayed: It catches all exceptions! and the routine that specifically handles this exception (and displays NameError exception in this case) will not be executed.
Errors that show up during the execution of the program and are not syntax errors belong to the so-called exceptions. The list of exceptions is quite extensive >>see<<
We can handle these exceptions by putting code that can cause an exception in a try block, i.e.
# Here we put code that can raise an exception or exceptions
and the code to handle the exception in the except block (equivalent to Java catch), i.e.
# Here we put the exception handling code
It is more useful to react to specific exceptions than to handle all of them “in bulk”. The except statement itself without specifying the name of the error class can be useful if you want to catch an exception that has not yet been handled by an earlier except block, e.g.
# Here we put the code to handle the ZeroDivisionError exception
# Here we put the code to handle the NameError exception
# Here we catch the remaining unhandled exceptions