Python Programming – Exception Handling
While writing Python code, certain errors may occur. In the first place, these errors can prevent the program from being executed by the interpreter. These errors are called compile-time errors. For an instance, forgetting to follow the exact syntax of a particular construct such as if statement or making a spelling mistake, missing a semicolon or colon, may cause an interpreter/compile-time error. The program gets executed only after these errors are rectified. Let us consider a program given in Code 8.1. This program determines whether a number is even. In the if statement, we see that colon (:) is missing. The execution of this code raises a syntax error as presented in Fig. 8.1.
- Introduction to Python Programming – Testing and Debugging
- Python Programming – Python Loops
- Python Programming – Assert Statement
Code: 8,1, Illustration of interpreter time error (syntax error).
# This program illustrates syntax error number=input(‘Enter a number:’) |
Exception
There exist some errors which occur at run time in the program. For instance, attempting to divide by zero or accessing a list, which is not defined, opening a file that does not exist are common examples of run time errors. The run time error is called an exception. By the occurrence of these errors, Python creates an exception object. If not handled properly, it prints a traceback to that error along with some details about why that error has occurred. For instance, consider a simple code given in code: 8.2. We see that there is no syntax error in this code, therefore it executes without any error. The output of this code is given in Fig. 8.2., We see if the user inputs the value of number as 0 then the expression c=15/number evaluates to c=15/0, then due to division by zero, zero division Error exception occurs and we don’t obtain the output.
Code: 8.2. Illustration of runtime error (Exception)
#This program illustrates run time error number=input(‘Enter a number) |
Python Built-in Exceptions
python language detects exceptions if they occur during the exception of a program. There exists numerous built-in python exception listed in Table 8.1. with the description of each.
Exception | Cause |
AssertionError | Raised when an assert statement fails. |
AttributeError | Raised when attribute assignment or reference fails. |
EOFError | Raised when the output( ) functions hit the end-of-file condition. |
FloatingPointError | Raised when a floating-point operation fails. |
GeneratorExit | Raise when a generator’s close( ) method is called. |
ImportError | Raised when the imported module is not found. |
IndexError | Raised when the index of a sequence is out of range. |
KeyError | Raised when a key is not found in a dictionary. |
Keyboardlnterrupt | Raised when the user hits the interrupt key (Ctrl+c or delete). |
MemoryError | Raised when an operation runs out of memory. |
NameError | Raised when a variable is not found in the local or global scope. |
NotlmplementedError | Raised by abstract methods. |
OSError | Raised when system operation causes the system-related error. |
OverflowError | Raised when the result of an arithmetic operation is too large to be represented. |
ReferenceError | Raised when a weak reference proxy is used to access a garbage collected referent. |
RuntimeError | Raised when an error does not fall under any other category. |
Toleration | Raised by next() function to indicate that there is no further item to be returned by the iterator. |
SyntaxError | Raised by the parser when a syntax error is encountered. |
IndentationError | Raised when there is incorrect indentation. |
TabError | Raised when indentation consists of inconsistent tabs and spaces. |
SystemError | Raised when interpreter detects an internal error. |
SystemExit | Raised by sys.exit() function. |
TypeError | Raised when a function or operation is applied to an object of incorrect type. |
UnboundLocalError | Raised when a reference is made to a local variable in a function or method, but no value has been bound to that variable. |
UnicodeError | Raised when a Unicode-related encoding or decoding error occurs. |
UnicodeEncodeError | Raised when a Unicode-related error occurs during encoding. |
UnicodeDecodeError | Raised when a Unicode-related error occurs during decoding. |
UnicodeTranslateError | Raised when a Unicode-related error occurs during translating. |
ValueError | Raised when a function gets argument of correct type but improper value. |
ZeroDivisionError | Raised when the second operand of division or modulo operation is zero. |
Summary
In this chapter, we have discussed interpreting time errors (syntax errors) and run-time errors. Run time errors are also called exceptions. Various built-in exceptions are available in the Python language. However, the user can create their own exceptions for handling different circumstances, which can occur during the execution of the program. All exception handling constructs try, except, finally are discussed with the programming illustration of each of them. User-defined exceptions are also discussed with examples.