Python Try Except
The try and except statements let your program catch errors as they happen and respond gracefully instead of crashing.
Why exception handling matters
When Python hits a problem it cannot resolve, such as dividing by zero or opening a file that does not exist, it raises an exception. If nothing handles that exception, the program stops and prints a traceback. Exception handling lets you anticipate these situations, catch them, and decide what should happen next, which keeps your program running and gives users a clear message instead of a raw error dump.
A basic try and except block
try:
number = int(input("Enter a number: "))
print("You entered", number)
except ValueError:
print("That was not a valid number.")How the blocks fit together
A full statement can have up to four kinds of clause. You always begin with try, follow it with one or more except clauses, and may optionally add else and finally. Each clause has a distinct job, and knowing when each one runs makes your error handling predictable.
Catching specific exceptions
It is good practice to catch the narrowest exception you expect rather than every possible error. You can list several except clauses to respond differently to different problems, and you can capture the exception object with the as keyword to inspect its message.
Handling more than one error type
values = [10, 0, "x"]
for v in values:
try:
result = 100 / int(v)
except ZeroDivisionError:
print("Cannot divide by zero")
except ValueError as err:
print("Bad value:", err)
else:
print("Result is", result)- List specific exception types so unexpected bugs are not silently swallowed.
- Use the as keyword to bind the exception to a variable when you need its details.
- A single except with a tuple, such as except (TypeError, ValueError), handles several types at once.
- Avoid a bare except that catches everything unless you re-raise or log the error.
The finally clause and cleanup
The finally clause is for cleanup that must happen no matter what, such as closing a connection or releasing a lock. Because it runs even when an exception propagates, it is the reliable place to put teardown code.
Guaranteed cleanup with finally
try:
print("Opening resource")
raise RuntimeError("something went wrong")
except RuntimeError as err:
print("Caught:", err)
finally:
print("This cleanup always runs")Raising your own exceptions
You can also raise exceptions deliberately with the raise keyword when your code detects a condition it should not continue past. This lets callers of your function handle the problem with their own try and except.
Exercise: Python Try...Except
What happens to the code inside a `finally` block?