LightMySky

Exceptions: Raising, Catching and Recovering

Signalling a failure by raising an exception, and handling it where the caller knows what to do about it. Catching everything and carrying on hides faults, so the choice of what to catch is the real skill.

No account needed. Progress saves in this browser.

What a learner can do afterwards

  • Catch a specific exception around a risky operation and recover from it
  • Raise an exception when a function is given input it cannot work with
  • Explain why catching every exception and continuing is usually the wrong repair

1 · Read

Failures arrive as exceptions with names. A missing file raises FileNotFoundError, while data in the wrong shape raises ValueError or IndexError. If nobody deals with them, the program crashes instead of recovering.

Try it together

You guard risky lines with try and catch one named error with except, adding the recovery beside it. A missing name gets a friendly ask to check the spelling. Flip it around with raise: when your function gets input it cannot work with, like a negative where only positives fit, you raise instead of returning a wrong answer.

A raised exception with no catcher prints an error and stops, while a caught one hands you a chance to fix the input or try another path. You catch the error you can fix and let the rest show, since each catcher owns one recovery.

Good to know

You never patch every failure with one shared catch all that carries on blindly. Catching everything hides faults and lets bad data travel further. An except block should recover with purpose, like a message or a retry, not just hide and hope.

Raise what you cannot use, catch the named error you can fix, and recover on purpose.

2 · Watch

Take it off screen

Print a worksheetA4 with an answer key page for grown-ups. No screen, no internet.

Where it sits

Then practise

8 questions wait behind this lesson, each with its answer explained. Every answer feeds the sky: stars light as they are learned, and dim when it is time to come back.

Spotted a problem on this page? Tell us
Exceptions: Raising, Catching and Recovering · Computing, ages 17 to 18 · LightMySky