← Learning Hub
Beginner

Errors and Files

When something goes wrong, Python raises an exception. Catch it with try / except so your program keeps running. finally always runs.

Things go wrong in real programs all the time: a user types letters instead of a number, a file is missing, the internet is down. Without handling, Python stops and shows an error message - your program crashes. With try / except, you expect the problem and decide what to do: show a friendly message, use a default, or try again.

Put only the risky line(s) in try. In except, name the exact error you expect (ValueError, ZeroDivisionError...). Catching every possible error with a bare except: hides real bugs, so avoid it.

Example
You can edit this code.
Example
You can edit this code.

Raising your own errors

Example
You can edit this code.

You can also raise errors yourself. This is how a function says "I can't work with this value". It's better than quietly returning a wrong answer, because the caller is forced to notice and handle the problem.

Reading and writing files

Use with open(...). It closes the file for you automatically, even if an error happens.

Files let your program remember things after it stops - saved orders, settings, reports. Variables disappear when the program ends; files stay on the disk. The with block opens the file, lets you work with it, and always closes it at the end, even if an error happens in between.

Example
You can edit this code.
File modes: "r" read (the default), "w" write (replaces the file), "a" add to the end.
Key points
  • try / except handles errors so the program doesn't crash.
  • Catch specific errors like ValueError; avoid a bare except.
  • raise reports a problem from your own code.
  • Use with open(...) for files; modes are "r", "w" and "a".

📝 Test yourself

1. Which block runs if an error happens inside try?
2. Why use with open(...)?
3. Fill in the keyword that causes your own error:
ValueError("bad")