Exception Handling

Exception Handling :

Like other languages, python also provides the runtime errors via exception handling method with the help of try-except. Some of the standard exceptions which are most frequent include IndexError, ImportError, IOError, ZeroDivisionError, TypeError.

Example 1:

# Python program to handle simple runtime error 

a = [1, 2, 3] 
try: 
    print("Second element = %d"%(a[1]))

    # Throws error since there are only 3 elements in array 
    print("Fourth element = %d"%(a[3]) )

except IndexError: 
    print("An error occurred")

Second element = 2

An error occurred

Example 2:

Error Occurred and Handled

Else Clause

Example 3:

-5.0

a/b result in 0

success

Example 4:

The entry is a

Oops! <class 'ValueError'> occured.

Next entry.

The entry is 0

Oops! <class 'ValueError'> occured.

Next entry.

The entry is 2

The reciprocal of 2 is 0.5

Last updated

Was this helpful?