Python - Error handling with try, except and finally statements

By xngo on June 20, 2019

Python provides try, except and finally statements to catch exceptions. An exception occurred when something is wrong and you can use these statements to handle it gracefully.

  • try: Try to run the code.
  • except: If an exception is raised while running the code, then run code in except statement.
  • finally: Regardless of whether the code in try failed or succeed, run the code in finally statement.

Here is an example showing how they work together.

try:
    print(x)
 
except:
    print("except: x doesn't exist.")
 
finally:
    print("finally: Regardless of whether or not try fail, I'm showing this line")

Output

except: x doesn't exist.
finally: Regardless of whether or not try fail, I'm showing this line

Reference

  • https://docs.python.org/3/tutorial/errors.html

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.