Catch errors as they happen, so one bad value doesn't crash the whole program.
# catch any exception
try:
result = 10 / 0
except:
print("Error occurred")
# ans: Error occurred
When a line raises an error, Python abandons the rest of the try block and jumps to except.
# catch a specific exception
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
# ans: Cannot divide by zero
# access exception details
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")
# ans: Error: division by zero
as e names the exception object; printing it shows its message.
# handle different exceptions
try:
value = int(input())
result = 10 / value
except ValueError:
print("Invalid number")
except ZeroDivisionError:
print("Cannot divide by zero")
# ans: no error: result is 2.0
# one handler for several types
try:
# code
pass
except (ValueError, TypeError):
print("Type or value error")
A tuple of exception types: the handler runs if the error is any one of them.
# else runs if there was no exception
try:
result = 10 / 2
except ZeroDivisionError:
print("Error")
else:
print("Success")
# ans: Success
# finally always runs
try:
file = open("data.txt")
except FileNotFoundError:
print("File not found")
finally:
print("Cleanup")
# ans: File not found, then Cleanup
# the full shape
text = "42"
try:
x = int(text)
except ValueError:
print("bad")
else:
print("ok", x)
finally:
print("done")
# ans: ok 42, done
text =
try → except or else → finally.
Predict what happens, then press → to trace.
# catch all exceptions?
try:
x = 1 / 0
except:
pass
# ans: catches everything (not recommended)
# what is e?
try:
x = 1 / 0
except ZeroDivisionError as e:
type(e)
# ans: <class 'ZeroDivisionError'> (e is a ZeroDivisionError instance)
# when does else run?
try:
x = 5
except:
print("Error")
else:
print("OK")
# ans: "OK" (no exception)
# finally with return?
def func():
try:
return 1
finally:
print("Finally")
func()
# ans: prints "Finally", then returns 1
# nested try?
try:
try:
x = 1 / 0
except ValueError:
pass
except ZeroDivisionError:
print("Caught")
# ans: "Caught"
An error the inner try doesn't handle travels outwards to the next try.
# multiple except order?
try:
x = 1 / 0
except Exception:
print("General")
except ZeroDivisionError:
print("Specific")
# ans: "General" (the first matching handler wins)
Put specific exceptions before general ones.
# finally without except?
try:
x = 5
finally:
print("Done")
# ans: valid, prints "Done"
# else without except?
try:
x = 5
else:
print("OK")
# ans: SyntaxError (else needs an except)
# exception in finally?
try:
x = 5
finally:
y = 1 / 0
# ans: raises ZeroDivisionError
# bare except position?
try:
x = 1 / 0
except ValueError:
pass
except:
print("Other")
# ans: "Other"
tryStops at the first error and jumps to a handler.
exceptHandlers are checked in order; the first that matches runs. A bare except catches everything.
elseRuns only when the try block raised nothing.
finallyAlways runs: after success, after a handled error, even before a return.