Python | Set 5 (exception handling)

File handling | Python Methods and Functions

Like other languages, python also provides runtime errors through the try-exc exception handling method. Some of the standard exceptions that are the most common include IndexError, ImportError, IOError, ZeroDivisionError, TypeError.

Exception is the base class for all exceptions in Python. You can check the exception hierarchy here .

Let's try to access to the array element whose index is out of bounds and handle the corresponding exception.

# Python program to handle simple errors at runtime


a = [ 1 , 2 , 3 ]


print " Second element =% d " % (a [ 1 ])


# Throws an error because there are only 3 elements in the array

print "Fourth element =% d" % (a [ 3 ]) 


except IndexError:

print "An error occurred"


 Second element = 2 An error occurred 

A try statement can have more than one condition, besides a clause, to specify handlers for various exceptions. Note that no more than one handler will be executed.

# Program for handling multiple errors with one operator except


a = 3

  if a & lt;  4 :


# throws a ZeroDivisionError for a = 3

b = a / (a - 3 )


# throws a NameError if a & gt; = 4

print "Value of b = " , b

# note that parentheses () are required here for multiple exceptions

except (ZeroDivisionError , NameError):

print " Error Occurred and Handled "


 Error Occurred and Handled 

If you change the value of 'a' to greater than or equal to 4, the output will be

 Value of b = Error Occurred and Handled 

The output above is this because as soon as python tries to access the value of b, a NameError occurs.

In python, you can also use the else clause in the block try-exc, which must be present after all clauses except. Code enters the else block only if the try clause does not throw an exception.

# Program to display the else clause with try-exc

# Function that returns a / b

def AbyB (a, b):

try :

c = ((a + b) / (a - b))

except ZeroDivisionError:

print "a / b result in 0 "

  else :

print c

# Driver program to test the above function

AbyB ( 2.0 , 3.0 )

AbyB ( 3.0 , 3.0 )

The output for the above program will be:

 -5.0 a / b result in 0 

Exception thrown:  
The lift operator allows the programmer to force a specific exception to be thrown. The only argument in a raise indicates an exception that should be raised. It must be either an exception instance or an exception class (a class derived from Exception).


# Program to render the exception



raise NameError ( " Hi there " # Promotion failed

except NameError:

print "An exception"

raise   # To determine if an exception was raised or not

The output of the above code will just be printed as an "Exception" string, but a runtime error will also occur in the latter because of the promotions operator on the last line. So your command line output will look like

 Traceback (most recent call last): File "", line 4, in raise NameError ("Hi there") # Raise Error NameError: Hi there 

This article is courtesy of Nikhil Kumar Singh (nickzuck_007)

Please write comments if you find something wrong or if you would like to share additional information on the topic under discussion