Sub topic 2
Inspecting Exceptions with `as`
Assume you can write functions, use basic control flow, read a traceback, and define simple classes. This chapter focuses on the parts of a try statement that control success, cleanup, and new errors.
Inspecting the exception with `as`
An except clause can bind the caught exception to a name with as. The exception object contains details such as its message and, for some types, useful attributes.
import json
def load_settings(text):
try:
return json.loads(text)
except json.JSONDecodeError as error:
print(f"Invalid JSON at line {error.lineno}, column {error.colno}")
return {}
print(load_settings('{"mode": }'))Catch the narrowest exception you can identify. A broad except Exception can hide programming errors that you should fix instead of handling.
Running the success path in `else`
The else block runs only when the try block completes without an exception. Keep risky operations in try, and put normal success processing in else.
def parse_port(text):
try:
port = int(text)
except ValueError as error:
print(f"Invalid port: {error}")
return None
else:
if not 0 < port < 65536:
raise ValueError("port is out of range")
return portGuaranteed cleanup with `finally`
The finally block runs whether the operation succeeds, raises an exception, or returns early. Use it for cleanup that must happen, such as closing a resource.
A context manager, used with with, is usually clearer for files and similar resources because it performs this cleanup automatically.
Control flow inside `finally`
A return, break, or continue in finally can override an exception or an earlier control-flow decision. This can silently discard a failure.
def hidden_error():
try:
raise RuntimeError("important failure")
finally:
return "error was swallowed"
print(hidden_error())Avoid control-flow statements in finally. Let the pending exception or return continue normally.
Raising exceptions with `raise`
Use raise when a function cannot provide a valid result. You can raise a built-in exception or a custom exception. A bare raise inside an except clause re-raises the current exception without losing its traceback.
def require_port(text):
try:
port = int(text)
except ValueError:
raise ValueError(f"not a number: {text!r}")
if not 0 < port < 65536:
raise ValueError(f"out of range: {port}")
return port
try:
require_port("abc")
except ValueError as error:
print(error)Exercise
Which block runs when the try block raises an exception: else or finally?
Show answer
finally runs. The else block runs only when try succeeds.