42 Exception Handling
Try following code
print(1/0)
You should see following error
Traceback (most recent call last): File “
This example seems meaningless why should we knowingly divide a number by zero. But, consider that we get this values from end user.
a = 1 # from user input
b = 0 # from user input
Or, we need to read a file from system and this filename is again given by user.
filename = "a.txt" # from user input
# try to read content with wrong file name
We will again get an error.
Solution is to surround would be problematic lines with try…except statements See below examples
42.1 Examples
42.2 try..except
42.3 try..except..else
Else part runs if there is no error.
42.4 try..except..else..finally
finally part always runs.
42.5 exception handling hierarchy
- see exception hierarchy in python document
- see following code for generating Python error classes hierarchy
- see this article about this topic too