Skip to content
Minute Campus.

Almost rightLesson 061 min

The error is caught, and then nothing happens

This function turns text into an age, and the code catches the error raised for a word like "forty" and then does nothing. No message, no log, and the function quietly returns no value. Much later another line does arithmetic with the missing value and crashes far from the cause. This is called swallowing an exception. The fix is to catch only the expected error and say what went wrong.

Remember

A hidden error is a bug you will meet later, with less information.

Transcript

The lesson, word for word.

Read it at your own pace, or search the page for a term.

The error is caught, and then nothing happens. Three seconds: what is wrong with that? This function turns text into an age. Give it digits, and you get a number. Give it the word forty, and Python raises an error, because a word is not a number. The code catches that error. And then it does this: pass. Nothing. No message, no log. The function quietly returns no value, and the program carries on. Much later, another line tries to do arithmetic with that missing value, and crashes there, far from the real cause. This is called swallowing an exception. Code written so that it never crashes often does it. The fix: catch only the error you expect, and say what went wrong. Here: age must be a number, and the value that was not. The rule: an error you hide is a bug you will meet later, with less information.

Questions? Comment on the lesson on YouTube

New lessons every day.

Follow Minute Campus where you already scroll.