L4Β·OOP & Errors
π¨Exceptions
try/except/else/finally and custom errors.
tryexceptraisecustom
Β§ 1try / except
Catch specific exception types. Bare except: catches everything (avoid).
Β§ 2else / finally
else runs if no exception. finally always runs β great for cleanup.
Β§ 3Raising
raise ValueError('bad input'). Custom exceptions inherit from Exception.
Example
1def parse_int(s):β2 try:β3 return int(s)β4 except ValueError as e:β5 print(f"can't parse {s!r}: {e}")β6 return Noneβ7 finally:β8 print("done")β9β10print(parse_int("42"))β11print(parse_int("oops"))βTry it live Β· Python runs in your browser
Loading playgroundβ¦
Checkpoint quiz
Question 1 / 2
When does finally run?