Python Exceptions

Python Exceptions can be literally read as “make an exception for this error.” Or in other words, you’re telling your program “it’s ok if this error happens, do this instead.”

These are mostly commonly handled via the tryexcept…statements. Meaning “try this thing, except if this error happens…do this.”

With great power comes great responsibility. The golden rule of exceptions: Whenever possible, it is critical to explicitly state your exception vs using a “catch-all.”

If your program is throwing an error, it’s tempting to use a try/except statement to punch your way past it. However, if you don’t truly understand why the error is happening and fix the root cause, how stable is your analysis or program?

try:
  print(x)
except:
  print("An exception occurred")

When you are deciding to use a try/except, walk down this path

  • Can you fix the root problem of your error first?
  • Can you explicitly state the error you’re getting, do you know why you’re getting it?
  • Last resort, use a general try/except statement.

Let’s take a look at a python exception code sample


Python Exceptions

In Python, exceptions are how you handle errors in your program. These can be beneficial, but should be avoided when possible. Go fix the root cause of your problem first.

Let's look at an example.

First, let's try printing a variable we haven't defined yet, this will throw an error and stop our program

In [1]:
print (x)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-606ad02f996c> in <module>
----> 1 print (x)

NameError: name 'x' is not defined

However, if we wanted to account for this, we could wrap our print statement in a try...except statement

In [2]:
try:
    print (x)
except:
    print ("No variable found")
No variable found

Even better would be to call out the exact error in the except statement. This furthers our grasp on our program. Instead of it controling us, we are controling it.

In [3]:
try:
    print (x)
except NameError:
    print ("Name Error, no variable found")
Name Error, no variable found

But really, I prefer to solve the root of the problem if I can...

In [4]:
x = "Sweet!"
print (x)
Sweet!
In [ ]:
 

Link to code above

Check out more Python Vocabulary on our Glossary Page