Friday 20 July 2018

Python Raising an Exception

Cited from the book "Python How to Program"

"""
The simplest form of raising an exception consists of the keyword raise, followed by
the name of the exception to raise. Exception names identify classes; Python exceptions are
objects of those classes. When a raise statement executes, Python creates an object of the
specified exception class. The raise statement also may specify arguments that initialize
the exception object. To do so, follow the exception class name with a comma (,) and the
argument (or a tuple of arguments). Programs can use an exception object’s attributes to dis-
cover more information about the exception that occurred. The raise statement has many
forms.

The arguments used to initialize an exception object can be referenced in an exception handler to perform an appropriate task.

An exception can be raised without passing arguments to initialize the exception object. In
this case, knowledge that an exception of this type occurred normally provides sufficient in-
formation for the handler to perform its task.

When code in a program causes an exception, or when the Python interpreter detects a
problem, the code or the interpreter raises (or throws) an exception. Some programmers
refer to the point in the program at which an exception occurs as the throw point—an
important location for debugging purposes. Exceptions are objects of classes that inherit from class Exception. If an exception occurs in a try,suite, the try suite expires (i.e., terminates immediately), and program control transfers to the first except handler (if there is one) following the try suite.

Next, the interpreter searches for the first except handler that can process the type of exception that occurred. The interpreter locates the matching except by comparing the raised exception’s type to
each except’s exception type(s) until the interpreter finds a match. A match occurs if the
types are identical or if the raised exception’s type is a derived class of the handler’s excep-
tion type. If no exceptions occur in a try suite, the interpreter ignores the exception han-
dlers for the try statement and executes the try statement’s else clause (if the statement
specifies an else clause). If no exceptions occur, or if one of the except clauses success-
fully handles the exception, program execution resumes with the next statement after the
try statement. If an exception occurs in a statement that is not in a try suite and that state-
ment is in a function, the function containing that statement terminates immediately and the
interpreter attempts to locate an enclosing try statement in a calling code—a process
called stack unwinding.

Python is said to use the termination model of exception handling, because the try
suite that raises an exception expires immediately when that exception occurs.
"""

No comments:

Post a Comment