#python
Apart from SyntaxError
, which is related to untenable Python code, the interpreter throws a variety of exceptions as indicators of errors. Some examples include ZeroDivisionError
, NameError
, etc. Standard exception names, such as these, in Python, are built-in identifiers, but not reserved keywords. Exceptions usually provide a traceback including the line causing the error, the line number, and the file name which can be useful for debugging.
Exceptions generated by Python can be handled using the try
and except
construct.
try:
f = open('myfile.txt')
except OSError as err:
print("OS error:", err)
except (ValueError, NameError):
print("An exception")
raise ValueError("This is also a NameError")
except TypeError as err:
raise OSError from err
else:
f.close()
finally:
...
- A
try
statement can have more than oneexcept
clause. Moreover, exceptions can be bundled together as a tuple. - At most, one handler will be executed which is the first matching
except
clause. - While writing
exception
clauses, it is best to be as specific as possible so that unexpected exceptions can be propagated on. try...except
has an optionalelse
clause which, when used, must be placed after allexcept
clauses and is useful for code that must be executed if thetry
clause does not raise an exception.- The
raise
statement allows an optionalfrom
clause which is useful when transforming exceptions. - The
try
statement has another optional clause calledfinally
which is used to define clean-up actions that must be executed under all circumstances.- Unhandled exceptions, or exceptions raised by the
except
statement are re-raised after the execution of thefinally
statement. - If
finally
contains abreak
,continue
, orreturn
, then unhandled exceptions are not re-raised. - If the
try
statement has abreak
,continue
, orreturn
statement, thefinally
clause will execute prior to these statements. - If both
finally
andtry
contain a return statement, then the return offinally
will take precedence.
- Unhandled exceptions, or exceptions raised by the