4. Raise

raise starts an exception from your own code. Write raise followed by an exception object:

  • ValueError("Invalid value") creates a ValueError object; the string is its message.
  • raise stops the current block immediately, exactly like a real error.
  • If nothing catches it, the program stops and shows ValueError: Invalid value.
  • Use raise inside if statements to reject invalid arguments.

Coming from JavaScript? raise is Python's throw. Write raise ValueError("...") instead of throw new Error("...").

#01

Raise a ValueError

Raise a ValueError with the message Invalid value. Running the program must stop with:

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

#02

Raise and catch

Inside a try block, raise a ValueError with the message Bad input. Catch ValueError and print Caught. Because the except block handles it, the program continues normally.

Print exactly:

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

#03

Raise from a function

Define set_age(age). If age < 0, raise a ValueError with the message Age cannot be negative. Otherwise, return age. Print set_age(30), then call set_age(-1) inside a try block that catches ValueError as error and prints the message.

Print exactly:

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

#04

Stop the rest of the try block

Define withdraw(balance, amount). If amount > balance, raise a ValueError with the message Not enough funds. Otherwise, return balance - amount. In a try block, print withdraw(100, 30) and then withdraw(100, 150). Catch ValueError as error and print the message. The second call stops the try block before its print() runs.

Print exactly:

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