How do you handle exceptions in Python?
Use try/except to catch specific exceptions, else for code that runs only on success, and finally for cleanup.
Python
Overview
Python uses `try/except` blocks for error handling. Unlike JavaScript, Python makes a strong distinction between the `except` clause (error path), `else` (success path), and `finally` (always runs). Catching the right exception type is key.
Key Points
- •`except ExceptionType` catches that specific exception always prefer specific types over bare `except`.
- •`except (TypeError, ValueError)` catches multiple exception types.
- •`else` block runs only if no exception was raised in `try` keeps success code separate.
- •`finally` always runs use it for cleanup (closing files, releasing locks).
- •Use `raise` to re-raise the current exception, `raise ExceptionType("msg")` to throw a new one.
Examples
Basic try/except
pythontry:
value = int(input("Enter a number: "))
except ValueError:
print("That's not a valid number.")Full try/except/else/finally
pythontry:
file = open("data.json")
data = json.load(file)
except FileNotFoundError:
print("File not found")
except json.JSONDecodeError as e:
print(f"Invalid JSON: {e}")
else:
process(data) # only runs if no exception
finally:
file.close() # always runs (or use 'with' to avoid this)Context manager (better than manual finally)
python# Preferred: 'with' handles closing automatically
with open("data.json") as file:
data = json.load(file) # file is closed even if an exception occursCustom exception class
pythonclass InsufficientFundsError(Exception):
def __init__(self, amount, balance):
super().__init__(f"Cannot withdraw {amount}: balance is {balance}")
self.amount = amount
self.balance = balance
try:
raise InsufficientFundsError(100, 50)
except InsufficientFundsError as e:
print(e)Pro Tip
Never use bare `except:` it catches `SystemExit`, `KeyboardInterrupt`, and `GeneratorExit`, which you almost never want to catch. At minimum use `except Exception:`, but specific exception types are best.