2. Error messages

When an exception is caught, you can keep its exception object with as:

  • except ValueError as error: catches a ValueError and assigns the exception object to error.
  • The exception object carries the message that describes what went wrong.
  • print(error) prints that message: it calls str(error), so the type name is not included.
  • The name after as is a normal variable, but it only exists inside the except block. str(error) gives you the message as a string.
  • If you do not know which exception may happen, catch Exception and inspect it: type(error).__name__ gives the type name as a string.
  • except Exception: catches almost any error. A bare except: also catches everything, but it hides bugs you did not expect, so avoid it.

Coming from JavaScript? A caught error exposes its text as error.message; in Python, use print(error) or str(error).

#01

Print the exception message

Catch the ValueError raised by int("abc") with as error and print the exception object.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#02

Put the message inside a sentence

Catch the ValueError raised by int("12.5") with as error. Print Failed: followed by the message using an f-string.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#03

Read a division message

Put print(10 / 0) inside a try block. Catch ZeroDivisionError with as error and print the exception object.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#04

Return the message from a function

Define describe_error(text) that tries to convert text with int(text) inside a try block. If it raises ValueError, catch it with as error and return str(error). If the conversion succeeds, return "ok". Print describe_error("ten").

Print exactly:

Create a free account to save your progress and unlock chapter 2.