Scripting > Scripting Basics


Handling Exceptions

Certain errors within a Python program can cause Python to raise an exception.  An exception that is not handled by the program will cause the program to display error information in the console window and halt the program.

 

Python provides structured exception handling with the following constructs:

 

try :

  try-group

except :

  except-group

[else :

  else-group]

 

try :

  try-group

finally :

  finally-group

 

In the try-except-else construct, if an exception is raised during execution of the try-group, the control immediately transfers to the first line of the except-group.  If no exception is raised during execution of the try-group, the control transfers to the first line of the else-group, if present.  If there is no exception raised and no else-group is specified, the control transfers to the first line after the except-group.

 

In the try-finally construct, control is transferred to the first line of the finally-group when either an exception is raised during the execution of the try-group or the try-group completes without an exception.

 

The two constructs cannot be combined into a try-except-finally construct, but the same effect can be obtained by making a try-except-else construct the try-group of a try-finally construct.

 

Example: Exception Handling

 

try :

    try :

        string_1.find(substring) # may raise an exception

    except :

        print substring + “ is not in “ + string_1

        # do some stuff that might raise another exception

        …

    else :

        print substring + “ is in “ + string_1

        # do some stuff that might raise another exception

        …

finally :

    print “No matter what, we get here!”

 

 

More exception handling information, including filtering on specific types of exceptions, exception handler chains, and raising exceptions, is provided in Python tutorials and references listed at the official Python website: www.python.org.