Python Tutorial_ Exception Handling
Python Tutorial_ Exception Handling
Home Python 2 Tutorial Python 3 Tutorial Advanced Topics Numerical Programming Machine Learning Tkinter Tutorial Contact
try:
f()
except ValueError as e:
print("got it :-) ", e)
Custom-made Exceptions
The best or the Pythonic way to do this, consists in defining an exception class which inherits from the Exception class. You will have to go through the chapter on "Object Oriented Programming" to fully understand
the following example:
class MyException(Exception):
pass
If you start this program, you will get the following result:
$ python3 exception_eigene_klasse.py
Traceback (most recent call last):
File "exception_eigene_klasse.py", line 4, in <module>
raise MyException("Was falsch ist, ist falsch!")
__main__.MyException: An exception doesn't always prove the rule!
So far the try statement had always been paired with except clauses. But there is another way to use it as well. The try statement can be followed by a finally clause. Finally clauses are called clean-up or
termination clauses, because they must be executed under all circumstances, i.e. a "finally" clause is always executed regardless if an exception occurred in a try block or not.
A simple example to demonstrate the finally clause:
try:
x = float(input("Your number: "))
inverse = 1.0 / x
finally:
print("There may or may not have been an exception.")
print("The inverse: ", inverse)
Let's look at the output of the previous script, if we first input a correct number and after this a string, which is raising an error:
"finally" and "except" can be used together for the same try block, as can be seen the following Python example:
try:
x = float(input("Your number: "))
inverse = 1.0 / x
except ValueError:
print("You should have given either an int or a float")
except ZeroDivisionError:
print("Infinity")
finally:
print("There may or may not have been an exception.")
The output of the previous script, if saved as "finally2.py", for various values looks like this:
else Clause
The try ... except statement has an optional else clause. An else block has to be positioned after all the except clauses. An else clause will be executed if the try clause doesn't raise an exception.
The following example opens a file and reads in all the lines into a list called "text":
import sys
file_name = sys.argv[1]
text = []
try:
fh = open(file_name, 'r')
text = fh.readlines()
fh.close()
except IOError:
print('cannot open', file_name)
if text:
print(text[100])
This example receives the file name via a command line argument. So make sure that you call it properly: Let's assume that you saved this program as "exception_test.py". In this case, you have to call it with
If you don't want this behaviour, just change the line "file_name = sys.argv[1]" to "file_name = 'integers.txt'".
import sys
file_name = sys.argv[1]
text = []
try:
fh = open(file_name, 'r')
except IOError:
print('cannot open', file_name)
else:
text = fh.readlines()
fh.close()
if text:
print(text[100])
The main difference is that in the first case, all statements of the try block can lead to the same error message "cannot open ...", which is wrong, if fh.close() or fh.readlines() raise an error.
© 2011 - 2018, Bernd Klein, Bodenseo; Design by Denise Mitchinson adapted for python-course.eu by Bernd Klein