Skip to content
dreamcode
dreamcode
Map
Raising errors
Lesson 40 of 77
+15 XP on finish
PYTHON INTERMEDIATEChapter 7 · Errors, Files and Modules

Raising your own errors

When a function receives something it cannot handle, raise an exception instead of quietly returning a wrong answer: raise ValueError("message"). The caller decides what to do with it using try/except. For problems specific to your program, create a custom exception by subclassing Exception.

Worked example

How it reads

  • raise stops the function immediately and sends the error up to the caller
  • class LaunchError(Exception) makes a new kind of error you can catch by name
  • except ... as e gives you the error, and print(e) shows its message
Cloud tip: Raise early, catch late: check inputs at the top of a function, and handle errors where you can actually do something about them.
main.py
PYTHON
real Python, runs in your browser
Console
Run your code to see its output here.
YOUR TURN

Make set_speed raise ValueError("speed must be positive") for negative speeds, so the program prints error: speed must be positive.

Press Run to check your work.