Managing exceptions
Exceptions are errors detected by Python during program execution. When the interpreter encounters an exceptional situation, such as trying to divide a number by 0 or trying to access a file that does not exist, it generates or throws an exception, informing the user that there is a problem.
If the exception is not captured, the execution flow is interrupted and the information associated with the exception in the console is displayed so that the programmer can solve the problem.
Let's see a small program that would throw an exception when trying to divide 1 by 0. If we execute it, we will get the following error message:
The first thing that is shown is the traceback, which consists of a list of the calls that caused the exception. As we see in the stack trace, the error was caused by the call to calculate () of line 7, which in turn calls division (1, 0) on line 5, and ultimately the execution of the a/b sentence of division line 2.
The Python language provides an exception-handling capability to do just this. We use try/except statements to provide exception-handling. Now, the program tries to execute the division by zero. When the error occurs, our exception-handling catches the error and prints a message to the screen:
In the following example, we try to create a file-type f object. If the file is not passed as a parameter, an exception of the IOError type is thrown, which we capture thanks to our try-except:
Some of the exceptions available by default are listed here (the class from which they are derived is in parentheses):
- BaseException: Class from which all exceptions inherit.
- Exception (BaseException): Super class of all exceptions that are not output.
- ZeroDivisionError (ArithmeticError): Launched when the second argument of a division or module operation was 0.
- EnvironmentError (StandardError): Parent class of errors related to input/output.
- IOError (EnvironmentError): Error in an input/output operation.
- OSError (EnvironmentError): Error in a system call.
- ImportError (StandardError): The module or the module element that you wanted to import was not found.