Python Programming - Exception Handling

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:’)
number=int(number)
if number%2==0
print(‘Number is even’)
print(‘out of if block’)

Python Programming - Exception Handling chapter 8 img 1

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)
number=int(number)
C=15/Number
Print(c)

Python Programming - Exception Handling chapter 8 img 2

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

AssertionErrorRaised when an assert statement fails.
AttributeErrorRaised when attribute assignment or reference fails.
EOFErrorRaised when the output( ) functions hit the end-of-file condition.
FloatingPointErrorRaised when a floating-point operation fails.
GeneratorExitRaise when a generator’s close( ) method is called.
ImportErrorRaised when the imported module is not found.
IndexErrorRaised when the index of a sequence is out of range.
KeyErrorRaised when a key is not found in a dictionary.
KeyboardlnterruptRaised when the user hits the interrupt key (Ctrl+c or delete).
MemoryErrorRaised when an operation runs out of memory.
NameErrorRaised when a variable is not found in the local or global scope.
NotlmplementedErrorRaised by abstract methods.
OSErrorRaised when system operation causes the system-related error.
OverflowErrorRaised when the result of an arithmetic operation is too large to be represented.
ReferenceErrorRaised when a weak reference proxy is used to access a garbage collected referent.
RuntimeErrorRaised when an error does not fall under any other category.
TolerationRaised by next() function to indicate that there is no further item to be returned by the iterator.
SyntaxErrorRaised by the parser when a syntax error is encountered.
IndentationErrorRaised when there is incorrect indentation.
TabErrorRaised when indentation consists of inconsistent tabs and spaces.
SystemErrorRaised when interpreter detects an internal error.
SystemExitRaised by sys.exit() function.
TypeErrorRaised when a function or operation is applied to an object of incorrect type.
UnboundLocalErrorRaised when a reference is made to a local variable in a function or method, but no value has been bound to that variable.
UnicodeErrorRaised when a Unicode-related encoding or decoding error occurs.
UnicodeEncodeErrorRaised when a Unicode-related error occurs during encoding.
UnicodeDecodeErrorRaised when a Unicode-related error occurs during decoding.
UnicodeTranslateErrorRaised when a Unicode-related error occurs during translating.
ValueErrorRaised when a function gets argument of correct type but improper value.
ZeroDivisionErrorRaised 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.

Python Tutorial

Leave a Reply

Your email address will not be published. Required fields are marked *