Input validation
Parse or validate external input while converting expected failures into a controlled result.
Python · Const
The try statement runs potentially failing code and can respond with matching except handlers. Optional else handles success-only work, while finally provides cleanup that runs regardless of the outcome.
A try statement groups code that may raise an exception with handlers and optional success and cleanup clauses. Python executes the try suite first; a matching except suite handles the error, else runs only when the try suite succeeds, and finally runs for cleanup.
try:
suite
except [expression [as identifier]]:
suite
else:
suite
finally:
suitetry:
value = int("42")
except ValueError:
value = 0
else:
print(value)
finally:
print("finished")Parses the value, handles a conversion failure, runs the else block only after success, and always runs the finally block.
Parse or validate external input while converting expected failures into a controlled result.
Release a file, lock, connection, or other resource after an operation completes or fails.
Separate successful post-processing from the code whose failure is being handled.
The try suite runs first. If it raises an exception, Python searches the except clauses and executes the first matching handler; otherwise, handlers are skipped and execution continues after the statement.
Follow-up: What happens to an unmatched exception? It propagates outward to an enclosing try statement, or terminates execution as an unhandled exception if no handler matches.
The else suite is optional and runs only when the try suite completes without raising an exception. It must appear after all except clauses.
Follow-up: Why place success-only code in else? It keeps that code outside the protected try suite, so exceptions it raises are not mistaken for failures of the attempted operation.
The finally suite is used for cleanup and runs regardless of whether the try suite succeeds or an exception is handled. A try statement may also use finally without except or else.
Follow-up: What if an exception remains unhandled? Python still executes finally before propagating the exception or reporting it as unhandled.
exceptelsefinallyBaseExceptionException