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 a ZeroDivisionError. If no error occurs, the except block is skipped.
  • The indented block under each line is a branch. In this lesson, try is always followed by an except block.
  • Name the exception type after except so only that error is caught. Common built-in types are ZeroDivisionError, ValueError, IndexError, KeyError and TypeError.
  • 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 bare except: 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.

#01

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.

#02

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.

#03

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.

#04

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.

#05

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.