9/10/26About 2 minAbout 229 words
Concept: Try, except, else, finally
Using try, except, else, and finally, it is possible to write code that handles errors gracefully. One should only use try when you expect an error to occur, not to catch general runtime errors as these usually indicate an error in the program instead of an external factor.
The blocks must be used in a set order and have the following meaning.
try:
# Code that might throw an error.
# Keep as little code as possible in the try block to avoid
# catching errors that you did not expect.
# Catch an error of a specific type.
# Use the generic `Exception` class to catch all errors, but
# this is not recommended as it can hide bugs in your code.
except ExceptionType:
# Handle the error
# OPTIONAL
except Exception:
# Handle a second error type
# There must be at least ONE except block, but there can be
# multiple except blocks to handle different error types.
# OPTIONAL
else:
# Code to run if no error occurred
# This is code that depends on the try block running successfully
# but is not expected to throw an error itself.
# OPTIONAL
finally:
# Code to run regardless of whether an error occurred or not