Python Programming – Exception Handling
When an exception occurs, the current process stops and passes it to the calling process until it is handled to obtain the result. If not handled properly, the program crashes and the intended output is not obtained and the program comes to a halt.
Try, Except, and Finally
In Java, try and catch blocks are used to handle exceptions, in Python, exceptions can be handled using a try and except statements. A critical operation that can raise an exception is included in the try clause and the code for handling the exception is included in except clause. Consider a programming example in Code: 8.3. In this program, we see that the user is asked to input an integer number and then its reciprocal will be computed. In the output, we see that if the user enters a character or float (real) value then the ValueError exception occurs, which is caught by the except clause, and the appropriate error message “please try again” along with the exception is displayed to the user.
The while loop executes until the user supplies a valid integer value as an input for the computation of valid reciprocal. The critical portion that can cause exceptions is placed inside the try block. If there is no exception then programs execute with normal flow and if an error occurs then it is caught by the except clause. Therefore, we see exception occurs three times for inputting a, 1.5, and 0 and handled by the except block of the .program by providing value error and divide by zero error messages. The code ex info module is used to fetch the type of exception from the sys module. Therefore, the sys module is necessary to import into this program.
Code: 8.3. Illustration of Try and Except clauses.
|# This program illustrates to handle exceptions using try and except clauses
print(“The reciprocal of’,x,”is”,r)
Enter an integer: a
Enter an integer: 1.5
Enter an integer: 0
Enter an integer: 5
Catching Specific Exceptions in Python
We can also handle exceptions separately rather than all exceptions in one block. In Python, a try clause can have multiple except clauses just like a try block can have multiple catch blocks in Java. Only one of them will be executed depending upon the type of occurred exception. The code for the same is illustrated in Code 8.4.
Code: 8.4. Illustration of multiple except clauses.
# do something
# handle ValueError exception
passexcept (TypeError, ZeroDivisionError):
# handle multiple exceptions
# TypeError and ZeroDivisionError
# handle all other exceptions
As we have- seen that the try statement can have multiple except statements. Alike Java, Python also exhibits an optional clause ‘finally’. It gets executed automatically and is mostly used to release external resources. For example, while developing some large projects, we may be connected to a server on the network or to a file of GUI. Then in such situations, to release all the resources finally exception clause can be used. It will ensure that all resources are freed up to guarantee the successful execution of the program. The program illustrating the same is displayed in Code 8.5.
Code: 8.5. Illustration of finally clause.
fp = open(“check.txt”,encoding = ‘utf-8’)
# perform file operations
Note: This type of construct makes sure the file is closed even if an exception occurs.
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.
Code: 8,1, Illustration of interpreter time error (syntax error).
|# This program illustrates syntax error
number=input(‘Enter a number:’)
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.
|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.|
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.