RUNTIME VALUE CONVERSIONS
Recover from supported runtime errors, continue processing, and run cleanup when a protected operation finishes.
Select Transpile → Runtime. These forms apply to Runtime conversion; Typed conversion retains its existing status-return interfaces.
Use a builtin exception name, a tuple of names, or a final bare except. Handlers are tested in source order and the first matching handler runs. An error from a called function propagates to the nearest matching handler, including across supplied modules.
def main():
for text in ["12", "bad", "0"]:
try:
result = 120 // int(text)
except (ValueError, ZeroDivisionError):
print("Cannot calculate:", text)
else:
print("Result:", result)
finally:
print("Checked:", text)
return 0
Expected output:
Result: 10 Checked: 12 Cannot calculate: bad Checked: bad Cannot calculate: 0 Checked: 0
else runs only when the try body finishes normally. A return, break, continue, or error skips it. Errors raised in an else block or a handler are handled by an enclosing try, not another handler of that same try statement.
| Handler | Matches |
|---|---|
ValueError, TypeError | Invalid admitted values or incompatible value types. ValueError also catches Unicode errors and an unsupported file read/write direction. |
ArithmeticError | ZeroDivisionError and OverflowError, including checked signed-64 overflow. |
ZeroDivisionError, OverflowError | The corresponding arithmetic error alone. |
LookupError | IndexError and KeyError. |
IndexError, KeyError | The corresponding index or key failure alone. |
NameError, UnboundLocalError | NameError includes UnboundLocalError; the latter catches a local read before assignment. |
AttributeError, AssertionError | An admitted attribute operation that fails, or a failed message-free assert. |
OSError | File open/read/write/close/positioning failures, FileExistsError, and unsupported read/write directions or relative text seeks. Other operating-system subclasses are not exposed. |
UnicodeError, UnicodeDecodeError | Invalid UTF-8 file input. UnicodeError includes UnicodeDecodeError. |
FileExistsError | Exclusive mode "x" cannot create a file because the destination already exists. Also caught by OSError or Exception. |
StopIteration | Explicit next without a default reaches exhaustion. Normal for-loop exhaustion does not enter a handler. |
RuntimeError | Recoverable runtime errors, such as prohibited mutation during iteration. |
Exception or bare except | All supported recoverable errors. Resource-policy failures remain terminal. |
Exception names must be unshadowed builtins. Imports, aliases, computed handler expressions, user-defined exception classes, and except … as error are outside this profile. The converter reports PYC4630 for an unsupported exception form.
A finally block runs once after normal completion, a caught or uncaught recoverable error, return, break, or continue. Nested cleanup runs from the innermost scope outward. The return expression is evaluated before cleanup; its selected value is retained while cleanup runs.
Runtime return-annotation checks apply to the final selected value after cleanup. Constructor checks likewise run after the initializer finishes. A failure of either boundary check is reported to the caller.
A return, break, or continue in finally replaces the earlier transfer and can suppress a recoverable error, following Python control flow. An error raised in finally replaces an earlier recoverable error. Prefer straightforward cleanup statements when suppressing an error is not your intent.
Cleanup code may call other supported functions. A handler starts with the earlier error cleared, allowing ordinary operations and further calls. If no handler matches, the original logical filename and line remain attached to the error as it propagates.
A file opened by a direct with open(...) closes when execution leaves its scope. A handler outside that scope sees the file already closed. A handler inside the scope can continue using the same open handle. If a later open fails, earlier handles from that with statement are also closed.
def main():
with open("counts.txt", "w", encoding="utf-8", newline="") as output:
try:
output.write("Start\n")
int("invalid count")
except ValueError:
output.write("Skipped invalid count\n")
finally:
output.write("Finished\n")
print("Closed:", output.closed)
with open("counts.txt", encoding="utf-8") as source:
print(source.read(), end="")
return 0
Expected output:
Closed: True Start Skipped invalid count Finished
Cleanup does not undo a write. Catching an error does not restore overwritten bytes or remove partial output. Modes "w" and "w+" truncate when the file is opened. See File-processing workflows for file options and limits.
Use raise ExceptionType, raise ExceptionType(), or one literal string message. The exception type must be one of the documented names above. UnicodeDecodeError is available for catching decoding failures; its multi-argument constructor is not supported.
def checked_count(count):
if count < 0:
raise ValueError("count must be nonnegative")
return count
def main():
try:
print(checked_count(-2))
except ValueError:
print("Please supply a nonnegative count.")
finally:
print("Validation finished.")
return 0
Expected output:
Please supply a nonnegative count. Validation finished.
as, bare re-raise, chaining with from, tracebacks, exception groups, and except* are not supported. Literal messages must be valid UTF-8 without embedded NUL.PC.error clear. An uncaught error keeps its message, logical filename, and line for the C caller. Discard its returned value and destroy the failed context. See Runtime C use.