1. Try and except
An exception is an error that stops the program when nothing handles it. A try statement lets you run code that may fail and catch that failure:
try:starts a block with the code that may raise an exception.except ZeroDivisionError:runs only if that block raises aZeroDivisionError. If no error occurs, theexceptblock is skipped.- The indented block under each line is a branch. In this lesson,
tryis always followed by anexceptblock. - Name the exception type after
exceptso only that error is caught. Common built-in types areZeroDivisionError,ValueError,IndexError,KeyErrorandTypeError. - If the block raises a different type, the handler is skipped and the error keeps going up to the caller. If nobody catches it, the program stops with a traceback:
- Use
except Exception:to catch almost any error. A bareexcept:catches everything, but it also hides bugs you did not expect, so avoid it.
Coming from JavaScript? try/except is Python's try/catch, but the caught type is written after except instead of in a separate variable.
Catch a zero division
Dividing by zero raises ZeroDivisionError. Put print(10 / 0) inside a try block and add an except ZeroDivisionError block that prints Cannot divide by zero.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Skip except when there is no error
Use a try/except ZeroDivisionError statement. Inside try, print 10 / 2. The division succeeds, so the except block must not run.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Catch a ValueError
int("abc") raises ValueError because "abc" is not a number. Put int("abc") inside a try block and add an except ValueError block that prints Not a number.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Return a fallback from except
Define safe_divide(a, b) that returns a / b inside a try block. If the division raises ZeroDivisionError, the except block must return 0. Print safe_divide(10, 2) and then safe_divide(10, 0).
Print exactly:
Create a free account to save your progress and unlock chapter 2.
An error that does not match keeps going
Define parse(text) that returns 10 / int(text) inside a try block, with an except ZeroDivisionError block that returns 0. Then call parse("abc") inside another try block whose except ValueError block prints ValueError escaped. The inner handler does not match a ValueError, so the error propagates to the outer one.
Print exactly:
Create a free account to save your progress and unlock chapter 2.