8. Errors and Exceptions
There are (at least) two distinguishable kinds of errors (general types): ==syntax errors and exceptions==.
Syntax errors, also known as parsing errors.
The parser repeats the offending line and displays little ‘arrow’s
pointing at the token in the line where the error was detected. The
error may be caused by the absence of a token before the indicated
token. In the example, the error is detected at the function print
,
since a colon (':'
) is missing before it. File name and line number
are printed so you know where to look in case the input came from a
script.
Even if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it. Errors detected during execution are called ==exceptions== and are not unconditionally fatal. Most exceptions are not handled by programs, however, and result in error messages as shown here:
Built-in Exceptions lists the built-in exceptions and their meanings.
Following example asks the user for input until a valid
integer has been entered, but allows the user to interrupt the program
(using Control-C
or whatever the operating system supports); note that
a user-generated interruption is signalled by raising the
==KeyboardInterrupt
== exception. :
The try
statement works as follows (with/without exceptions occuring).
- First, the try clause (the statement(s) between the
try
andexcept
keywords) is executed. - If no exception occurs, the except clause is skipped and execution
of the
try
statement is finished. - If an exception occurs during execution of the
try
clause, the rest of the clause is skipped. Then, if its type matches the exception named after theexcept
keyword, the except clause is executed, and then execution continues after the try/except block. - If an exception occurs which does not match the exception named in the
except clause, it is passed on to outer
try
statements; if no handler is found, it is an unhandled exception and execution stops with an error message.
A try
statement may have more than one except clause, to specify
handlers for different exceptions. At most one handler will be executed.
Handlers only handle exceptions that occur in the
==corresponding try clause==, not in other handlers of the same try
statement.
An except clause may name multiple exceptions as a parenthesized tuple, for example:
A class in an except
clause matches exceptions which are instances of
the class itself or one of its derived classes (but not the other way
around --- an except clause listing a derived class does not match
instances of its base classes). For example, the following code will
print B, C, D in that order:
When an exception occurs, it may have associated values, also known as
the exception’s arguments. The presence and types of the arguments
depend on the exception type.
The except clause may specify a variable after the exception name. The
variable is bound to the exception instance which typically has an
args
attribute that stores the arguments. For convenience, builtin
exception types define object.__str__
to print all the arguments
without explicitly accessing .args
. :
What is the base class for all exceptions and difference between Exception
subclass?
BaseException
is the common base class of all exceptions. One of its
subclasses, Exception
(user-defined exceptions), is the base class of all the
non-fatal exceptions. Exceptions which are not subclasses of Exception
are not
typically handled, because they are used to indicate that the program should
terminate. They include SystemExit
which is raised by sys.exit
and
KeyboardInterrupt
which is raised when a user wishes to interrupt the program.
Is possible to catch all exceptions with Exception
?
Exception
can be used as a wildcard that catches (almost) everything. However,
it is good practice to be as specific as possible with the types of exceptions
that we intend to handle, and to allow any unexpected exceptions to propagate
on.
How to use of Exception
to print or log the exception?
The most common pattern for handling Exception
is to print or log the
exception and then re-raise it (allowing a caller to handle the
exception as well):
The try
… except
statement has an optional else clause, which,
when present, must follow all except clauses. It is useful for code
that must be executed if the try clause does not raise an exception.
For example:
When else
block of try
… except
statement is better to use?
The use of the else
clause is better than adding additional code to the try
clause because it avoids accidentally catching an exception that must be
trigger by the try
… except
block.
Can we catch exceptions in deeply nested code?
Yes. Exception handlers do not handle only exceptions that occur immediately
in the try clause, but also those that occur inside functions that are
called (even indirectly) in the try clause. For example:
How to manually raise an exception?
The raise
statement allows the programmer to force a specified
exception to occur. For example:
If an exception class is passed to raise
how it will be processed?
It will be implicitly instantiated by calling its constructor with no arguments:
What if you need to catch exception do something and then re-raise it?
If you need to determine whether an exception was raised but don’t
intend to handle it, a simpler form of the raise
statement allows you
to re-raise the exception:
Exception Chaining, what if an unhandled exception occurs inside an except
section?
If an unhandled exception occurs inside an except
section, it will have the
exception being handled attached to it and included in the error message:
How to indicate that an exception is a direct consequence of another,
The raise
statement allows an optional from
clause:
This can be useful when you are transforming exceptions. For example:
It also allows disabling automatic exception chaining using the from None
idiom:
For more information about chaining mechanics, see Built-in Exceptions
Programs may name their own exceptions by creating a new exception class
Exceptions should typically be derived from the ==Exception
== class, either
directly or indirectly.
Most exceptions are defined with names that end in "Error", similar to
the naming of the standard exceptions.
Many standard modules define their own exceptions to report errors that
may occur in functions they define.
If a finally
clause is present, the finally
clause will execute as
the last task before the try
statement completes. The finally
clause runs whether or not the try
statement produces an exception.
If an exception occurs during execution of the try
clause, the
exception may be handled by an except
clause. If the exception is
not handled by an except
clause, the exception is re-raised after
the finally
clause has been executed.
An exception could occur during execution of an except
or else
clause. The
exception is re-raised after the !finally
clause has been executed.
If the finally
clause executes a break
, continue
or return
statement,
exceptions are not re-raised.
If the try
statement reaches a break
, continue
or return
statement, the
finally
clause will execute just prior to the break
, continue
or
return
statement’s execution.
If a finally
clause includes a return
statement, the returned value will be
the one from the ==finally
clause’s== return
statement, not the value from
the try
clause’s return
statement. For example:
A more complicated example:
When the finnaly
clause (try
) is useful in real world applications?
In real world applications, the finally
clause is useful for releasing
external resources (such as files or network connections), regardless of
whether the use of the resource was successful.
Look at the following example, which tries to open a file and print its contents to the screen:
What the problem with this code?
Is that it leaves the file open for an indeterminate amount of time after this
part of the code has finished executing.
The with
statement allows objects like files to be used in a way that ensures
they are always cleaned up promptly and correctly:
After the statement is executed, the file f is always closed, even if
a problem was encountered while processing the lines. Objects which,
like files, provide predefined clean-up actions will indicate this in
their documentation.
There are situations where it is necessary to report several exceptions
that have occurred. This is often the case in concurrency frameworks,
when several tasks may have failed in parallel, but there are also other
use cases where it is desirable to continue execution and collect
multiple errors rather than raise the first exception.
The builtin ==ExceptionGroup
== wraps a list of exception instances so that
they can be raised together. It is an exception itself, so it can be
caught like any other exception:
By using ==except*
== instead of except
, we can selectively handle only
the exceptions in the group that match a certain type. In the following
example, which shows a nested exception group, each these clause
extracts from the group exceptions of a certain type while letting all
other exceptions propagate to other clauses and eventually to be
reraised:
Note that the exceptions nested in an exception group must be instances, not types. This is because in practice the exceptions would typically be ones that have already been raised and caught by the program, along the following pattern:
When an exception is created in order to be raised, it is usually
initialized with information that describes the error that has occurred.
There are cases where it is useful to add information after the
exception was caught. For this purpose, exceptions have a method
==add_note(note)
== that accepts a string and adds it to the exception’s
notes list. The standard traceback rendering includes all notes, in the
order they were added, after the exception: