The 6 AI Engineering Patterns, come build with Greg live: Starts Jan 6th, 2025
Leverage
Glossary

Exception

Handle Python exceptions with try and except. Emphasize explicit error handling over catch-all approaches

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 most 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.

Link to code

On this page

No Headings