▶ Sign up free for the video, slides & prompts
The lesson below is open to all. Enter your email once to unlock every video, slide deck, prompt and code example on this device.
Checking…
Errors and try/except
Handle bad input without crashing.
🎬 Video version coming soon — read it now
Programs meet bad input, missing files and network failures. Instead of crashing, you can catch errors and respond sensibly.
The basic shape
Python runs the try block. If a ValueError happens, it jumps to except instead of crashing.
Keep asking until it's right
Combine it with a loop and a function:
Now every place in your program that needs a number can use ask_int.
Catching different errors
else and finally
Don't catch everything
A bare except: with pass silences all errors, so the program "works" but quietly gives wrong results. Catch the specific error you expect and do something useful with it.
Raising your own errors
raise stops bad data early, with a clear message, instead of letting it cause strange bugs later.
In one line
try runs risky code, except handles the specific errors you expect, and raise stops bad data with a clear message.
Share with a friend