Errors
Exceptions
When no exception is raised, the else block runs. Keeping success in else makes the try block contain only the operation that might fail.
Source
def parse_int(text):
return int(text)
text = "42"
try:
number = parse_int(text)
except ValueError:
print(f"{text}: invalid")
else:
print(f"{text}: {number}")
finally:
print(f"checked {text}")Output
42: 42
checked 42When parsing fails, int() raises ValueError. Catching that specific exception makes the expected recovery path explicit.
Source
text = "python"
try:
number = parse_int(text)
except ValueError:
print(f"{text}: invalid")
else:
print(f"{text}: {number}")
finally:
print(f"checked {text}")Output
python: invalid
checked pythonBare except: and broad except Exception: swallow far more than the failure you meant to handle, including KeyboardInterrupt (bare) and most programming bugs (broad). Catch the specific class — ValueError here — so unexpected failures still surface.
Source
def safe_parse_broken(text):
try:
return int(text)
except Exception:
return None
def safe_parse_fixed(text):
try:
return int(text)
except ValueError:
return None
print(safe_parse_broken("42"))
print(safe_parse_fixed("42"))Output
42
42Notes
- Catch the most specific exception you can.
elseis for success code that should run only if thetryblock did not fail.finallyruns whether the operation succeeded or failed.- Avoid bare
except:and broadexcept Exception:— they hide bugs and absorb signals likeKeyboardInterrupt.
See also
- prerequisite: Conditionals
- prerequisite: Guard Clauses
- related: Custom Exceptions
- related: Warnings
Run the complete example
Expected output
42: 42
checked 42
python: invalid
checked python
42
42
Execution time appears here after you run the example.