Content description:
- Python exception handling
- Hierarchy of exceptions
- Optional blocks: else and finally
Errors that show up during the execution of the program and are not syntax errors belong to the so-called exceptions.
You can handle these exceptions by putting code that can cause an exception in a try block, and the code to handle the exception in the except block:
try:
# put here a code that can raise an exception or exceptions
except:
# put here the exception handling code
It is more useful to respond to specific exceptions rather than to handle them all "in bulk".The exception statement itself without specifying the error class name can be useful if you want to catch an exception that has not yet been handled before:
except ZeroDivisionError:
# put here a code to handle the ZeroDivisionError exception
except NameError:
# put here a code to handle the NameError exception
except:
# catch the remaining unhandled exceptions here
You can assign the exception to a variable and display it in the handler:
except NameError as e:
print('Message:', e)
You can also create a common handler for several exceptions by putting class names in a tuple:
except (ZeroDivisionError, NameError):
# put here a handler for these two exceptions
Pay attention to the exception hierarchy. Parent exception classes are handled before child classes. Incorrect order will cause the exception to be handled within a more general procedure.
except Exception:
print('It catches all exceptions!')
except NameError:
print('NameError exception')
In the above example, the NameError exception will be handled by the first exception block.There is an optional else procedure that is executed only if there is no exception in the associated try block.
If an else block is present, it must follow the except block.
There can only be one else block (or none).
There is an optional block - finally that executes regardless of whether an exception exists.
If there is a finally block, it should be placed last and there can only be one.
The final block is mainly used to release access to external resources, e.g. a database.