Scripting >> Python >> Examples >> Exception Handling >> How to use try-except-else-finally to catch and handle exceptions

 

The try block lets you test a block of code for errors.

The except block lets you handle the error.

The finally block lets you execute code, regardless of the result of the try- and except blocks.

 Example 1: Basic Try Except block

Code
# import module sys to get the type of exception
import sys
Denominators = ['a', 0, 2]
for denominator in Denominators:
    try:
        print("The denominator is [{}]".format(str(denominator)))
        r = 1/int(denominator)
        break
    except:
        print("Error : {} occurred.".format(sys.exc_info()[0]))
        print("\n.. Go to next denominator ..\n")
print("The integer reciprocal of {} is {} ".format(denominator,r))
Output
The denominator is [a]
Error : <type 'exceptions.ValueError'> occurred.

.. Go to next denominator ..

The denominator is [0]
Error : <type 'exceptions.ZeroDivisionError'> occurred.

.. Go to next denominator ..

The denominator is [2]
The integer reciprocal of 2 is 0

 

Example 2: Basic Try..Except..Else..Finally block

 

Code

myfriendsage = { 'Tom' : 20, 'Dick' : 30, 'Harry' : 40 }
Proceed = True
while Proceed :
  name = raw_input("\nEnter friend's name: ")
  if name != "Quit":
    try:
      age = myfriendsage[name]
    except:

      # when there is error
      print("{} is not my friend".format(name))
    else:
      # when there is no error
      print("my friend {} is {} years old".format(name,myfriendsage[name]))
    finally:
      # do the following regardless of error or not
      print("I have checked my friends database and responded")
  else:
    Proceed = False

Output


Enter friend's name: Dick
my friend Dick is 30 years old
I have checked my friends database and responded

Enter friend's name: Mary
Mary is not my friend
I have checked my friends database and responded

Enter friend's name: Quit