Python Try Except

I’ve been hearing this question a lot, “how do I do a try catch in python“, and sometimes “how to i ignore an exception in python and keep going“. I think these are both asking the same thing. In fact, I don’t think we want to ever ignore an exception, and every time one is triggered, we should be investigating why it’s occurring. Furthermore, finding out why exceptions are happening should be followed up with a bug fix ;-). Well, enough best practice ranting, let’s get to it! Here’s a very simple try except clause in python:

try:
print("Trying some code")
anArray = [1,2,3]
# This will trigger an out of index exception
print(anArray[4]))
except Exception, e
print("An exception has occurred.")
print(e)

"""
Even though the above exception
is triggered, your code below still runs
"""
var i = 10
print(i)

Want To Work From Home? Take This Online Course To Find Out How

You can catch specific Exceptions if you know which to look for, but the generic Exception handler above will catch them all. It is actually really good practice to catch them individually, as you will find yourself having to address each scenario differently so you may want to have those hooks in place ahead of time.

For more on Errors in python check our this python tutorial on errors.

Start Your Freelance Career Today – Click Here To Find Out How

Leave a comment