try:
protected code
except ExceptionName1 as e1:
error handling code
except ExceptionName2 as e2:
error handling code
except ExceptionName3:
error handling code
except:
unconditional error handling code
raise # re-raises the exception
else:
code to execute if the try completes successfully.
This code is non-protected code (i.e., code we do not
expect to cause an exception)
finally:
code executed regardless of whether an exception occurs, and
regardless of whether an exception is handled if one occurs
Here is an example from the Python tutorial:
import sys
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except IOError as e:
print ("I/O error({0}): {1}".format(e.errno, e.strerror))
except ValueError:
print ("Could not convert data to an integer.")
except:
print ("Unexpected error:", sys.exc_info()[0])
raise
The try mechanism operates as follows:
It is permissable to write user-defined exceptions, which we will consider in the section on user exceptions.
except (RuntimeError, TypeError, NameError):Make sure that the list is parenthesized. Old-style Python allowed you to bind a variable to an exception object using the syntax:
except Exception, variableso if you omit the parentheses in the above statement, Python will try to bind the variable named TypeError to the exception object for RuntimeError, which is not what you intend.
except Exception as variable:For example:
except IOError as e:e.args will contain a list of the arguments passed to the exception object.
except Exception: ... except IOError: ...The "except IOError" will never get executed because an exception will always match the first clause.
raise NameError('HiThere')
raisein an except clause. It will then re-raise the exception by passing the exception to an outer try clause. Obviously this should be the last statement in your except clause.
class NameError(Exception): pass
try:
raise NameError('Hi There', 5)
except NameError as e:
for v in e.args:
print (v)
produces the output:
Hi There 5
class NameError(Exception):
def __init__(self, name, value):
self.name = name
self.value = value
try:
raise NameError('Hi There', 5)
except NameError as e:
print ('NameError:', e.name, "and error code =", e.value)
class NameError:
pass
try:
raise NameError('Hi There', 5)
except NameError as e:
for v in e.args:
print (v)
then you will get the error message:
TypeError: this constructor takes no argumentsThe reason is that NameError is no longer a subclass of Exception and hence there is no default constructor that converts the constructor's arguments to a list that is placed in the args attribute.