Programming foundations

Stage 1 · Lesson 8 of 9

Handling errors with exceptions

Your first language

Some errors are expected. A user types "abc" when you asked for a number, or a file is missing. try and except handle these without crashing the program.

Put the risky line inside try, catch the specific , such as ValueError or FileNotFoundError, and respond with a clear message or a retry. Catch the narrowest exception you can. A bare except: catches everything, so it hides real bugs, including typos in your own code.

An else block runs when nothing failed, and finally always runs, which suits clean-up work such as closing a file. You can raise your own exceptions too, such as raise ValueError("age must be positive"), to stop bad data early. Combine this with a to keep asking until the value is valid.

A question to check yourself, an AI practice session and 1 cheat sheet entry come when you add the roadmap to your account. Add it

Resources for this stage

Start with· follow one of these

Practise

  • Small exercises in your language track, with free feedback from a human mentor

Keep handy

  • The official tour: read the matching chapter after the course covers a topic

  • Quick syntax lookups and an online compiler for testing a snippet on a shared computer

Mark this stage as not done?