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

Exceptions

Use try and except blocks to handle exceptions. This prevents your program from crashing when a runtime error occurs.

Worked example

How it reads

  • try: wraps the code that might fail at runtime
  • except ValueError: catches and handles specific ValueErrors
Cloud tip: Always catch specific errors (like ValueError or KeyError) instead of a generic Exception.
main.py
PYTHON
real Python, runs in your browser
Console
Run your code to see its output here.
YOUR TURN

Convert the text "12x" with int() inside a try block, catch ValueError, and print not a number.

Press Run to check your work.