An exception is an error that occurs while a program is running, causing the program to abruptly halt. Some exceptions cannot be avoided regardless of how carefully a program is written.
Python,
like most modern programming languages, allows you to write code that responds to
exceptions when they are raised, and prevents the program from abruptly
crashing. Such code is called an exception handler and is written with
the try/except statement. There are several ways to write a try/except
statement, but the following general format shows the simplest variation:
try:
statement
statement
etc.
except
ExceptionName:
statement
statement
etc.
First the key word try appears, followed by a colon. Next, a code block appears which we will refer to as the try suite. The try suite is one or more statements that can potentially raise an exception.
After the try suite, an except clause appears.
The except clause begins with the key word except, optionally followed by the
name of an exception, and ending with a colon. Beginning on the next line is a
block of statements that we will refer to as a handler.
When the try/except statement executes, the
statements in the try suite begin to execute. The following describes what
happens next:
• If a statement in the try suite raises an
exception that is specified by the ExceptionName in an except clause,
then the handler that immediately follows the except clause executes. Then, the
program resumes execution with the statement immediately following the
try/except statement.
• If a statement in the try suite raises an
exception that is not specified by the ExceptionName in an except
clause, then the program will halt with a traceback error message.
• If the statements in the try suite execute without raising an exception, then any except clauses and handlers in the statement are skipped and the program resumes execution with the statement immediately following the try/except statement.
Handling Multiple Exceptions
In many cases, the code in a try suite will be
capable of throwing more than one type of exception. In such a case, an except
clause for each type of exception has to be written that you want to handle.
def main():
# Initialize
an accumulator.
total = 0.0
try:
# Open the sales_data.txt file.
infile = open('sales_data.txt', 'r')
# Read the values from the file and
# accumulate them.
for line in infile:
amount = float(line)
total += amount
# Close the file.
infile.close()
# Print the total.
print(format(total, ',.2f'))
except
IOError:
print('An error occured trying to read the file.')
except ValueError:
print('Non-numeric data found in the file.')
except:
print('An error occured.')
# Call the main function.
main()
If an exception occurs in the try suite, the Python
interpreter examines each of the except clauses, from top to bottom, in the
try/except statement. When it finds an except clause that specifies a type that
matches the type of exception that occurred, it branches to that except clause.
If none of the except clauses specifies a type that matches the exception, the
interpreter branches to the except clause.
Using One except Clause to Catch All Exceptions
Sometimes you might want to write a try/except statement
that simply catches any exception that is raised in the try suite and,
regardless of the exception’s type, responds the same way. This can be accomplished
by a try/except statement by writing one except clause that does not specify a
particular type of exception.
def main():
# Initialize
an accumulator.
total = 0.0
try:
# Open the sales_data.txt file.
infile = open('sales_data.txt', 'r')
# Read the values from the file and
# accumulate them.
for line in infile:
amount = float(line)
total += amount
# Close the file.
infile.close()
# Print the total.
print(format(total, ',.2f'))
except:
print('An error occured.')
# Call the main function.
main()
Displaying
an Exception’s Default Error Message
When
an exception is thrown, an object known as an exception object is
created in memory. The exception object usually contains a default error
message pertaining to the exception. When an except clause is written, the
exception object can be optionally assigned to a variable, as shown here:
except
ValueError as err:
This
except clause catches ValueError exceptions. The expression that appears after
the except clause specifies that we are assigning the exception object to the
variable err.
The
else Clause
The
try/except statement may have an optional else clause, which appears after all
the except clauses. Here is the general format of a try/except statement with
an else clause:
try:
statement
statement
etc.
except
ExceptionName:
statement
statement
etc.
else:
statement
statement
etc.
The
block of statements that appears after the else clause is known as the else
suite. The statements in the else suite are executed after the statements
in the try suite, only if no exceptions were raised. If an exception is raised,
the else suite is skipped.
The
finally Clause
The
try/except statement may have an optional finally clause, which must appear after
all the except clauses. Here is the general format of a try/except statement
with a finally clause:
try:
statement
statement
etc.
except
ExceptionName:
statement
statement
etc.
finally:
statement
statement
etc.
The
block of statements that appears after the finally clause is known as the finally
suite. The statements in the finally suite are always executed after the
try suite has executed and after any exception handlers have executed. The
statements in the finally suite execute whether an exception occurs or not. The
purpose of the finally suite is to perform cleanup operations, such as closing
files or other resources.