In many programming languages, exceptions are events which can be triggered and handled during program execution. They you to break the normal flow of execution in order to handle specific events such as errors or exceptions. The language provides some mechanism for both raising and handling exceptions during program execution.
an exception and handle thhandling exceptions so your program can take counter measures to deal with the specific event. If the exception is not handled, the program will abort with a runtime error.
A classic use of exceptions is in dealing with run-time errors.
For example, if you attempt to access a list element that is out of range, Python raises the IndexError
exception. In the following code segment
we attempt to print the item of the list at element $4$. But the legal range of indices is [0..3]. In this case, Python will automatically raise a specific exception to flag an error.
Traceback (most recent call last): File "<stdin>", line 1, in ? IndexError: list index out of range
By default, the exception causes the program to abort. To prevent this from happening, we can catch the exception and take counter measures such as printing a warning message.
The try
block encloses the group of statements for which you want
to catch exceptions. It must be followed by one or more except
blocks. Exception handling works as follows:
try
block are executed as normal.
except
block is skipped.
except
statement. If it matches, the except
block is executed and execution continues after the try
block.
except
block, the exception is passed up to outer try
blocks. If no matching except
blocks are found, it becomes an unhandled exception and the program terminates with a message similar to that shown earlier.
Exception handlers are very useful when extracting user input.
A try
block can contain multiple except
blocks.
In this case, we’ve added an exception handler to also catch divisions by zero. Without the handler, the program would abort since our program is incorrect and we are attempting to divide by zero. The last except
block can omit the exception type in order to catch any exception.
In some instances we may want to abort the program any way, even if we catch the exception. By catching the exception first, we can abort cleanly to clean up any loose ends. For example, if we have an output file opened, we may want to close it before the program aborts so the buffer is flushed.
The try
blocks can be used at any position within a program. When
an exception is raised, it is passed up to an earlier try
block
if it is not handled by a local try
block.
Python defines a number of built-in exceptions that can be raised automatically during program execution:
We have seen several instances when Python automatically raises exceptions during program execution. But you can also raise
an exception within your program
Python also defines the assert
statement which can be used to
make assertions within your program. This is very useful for debugging programs.
If the test
fails, an AssertionError
is raised. The string argument is passed as an argument to the exception object. The prototype of the assert
statement is
assert <test>, <data>
where the <data>
part is optional.