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?

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

commandthatdoesnotexist
 x = 1 + 1
 print(x)

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

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

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

Here is the output of the program after it runs:

Got into this exception. Program will continue
2

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 *