How Do You use the Built-in Exception Handling Functionality of Python?

Problem scenario
You want to use the built-in exception handling in your Python program. You know some part or parts of the code may throw an error. How do you use the "except" keyword?

Use the "try" key word. Here is an example of a program that throws an error:

 x = 1 + 1

Traceback (most recent call last):
File "", line 1, in
NameError: name 'commandthatdoesnotexist' is not defined

Here is a re-write of the same program with the "except" keyword:

 except NameError:
   print("Got into this exception.  Program will continue")
x = 1 + 1

Here is the output of the program after it runs:

Got into this exception. Program will continue

There are many other errors beside "NameError" that can be supported by except.

With "SyntaxError", it does not catch any Syntax Error. It only catches those arising from eval, exec or import (as explained here).

If you want to learn more about the except feature, see this external posting.

Leave a comment

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