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 inexcept
statement.finally
: Regardless of whether the code intry
failed or succeed, run the code infinally
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