Start learning free

LESSON 609 OF 635 · OBJECT-ORIENTED PROGRAMMING

Errors and Exceptions in Python in Python

Lesson

TL ; DR:

When a method can't do what it was asked, it raises an error. The code that called it catches the error with try and except.


def spend(self, amount):
    if amount > self.money:
        raise ValueError("not enough money")

    self.money -= amount

try:
    wallet.spend(80)
except ValueError as e:
    print("error:", e)


Full lesson:

Some requests can't be done. A wallet with 50 can't spend 80.

The method could return a special value, like -1. But the caller may forget to check it. Then the program goes on with a wrong number.

An exception is better. It is an error that the program can't miss.

Raising an error

  • raise ValueError("not enough money") stops the method at once.
  • The lines after it don't run. So the wallet keeps its money.
  • ValueError is Python's built-in error for a bad value.
  • The text in the parentheses is the error's message.

Catching it

  • Put the call inside a try block.
  • When the call raises an error, the rest of the try block is skipped.
  • Python runs the except ValueError as e block instead. e is the error.
  • Printing e shows its message.
  • Then the program goes on below the except block.

An error that nobody catches stops the whole program. Python prints the error and the line where it happened.


Your task

A Wallet starts with 50. Its spend method takes money out and returns what is left.

  • In spend, raise a ValueError when amount is more than self.money. Its message is "not enough money".
  • In the loop, call spend inside a try block. Print what was spent and what is left.
  • Catch the ValueError. Print error: and its message.

The loop tries to spend 20, then 40, then 30.

Expected output:

spent 20, 30 left
error: not enough money
spent 30, 0 left
STEP 1 OF 3
    Ctrl + Enter to check

    Raising Errors in Python

    Keep going with Python500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free