Errors are normal — Python raises exceptions, and try/except lets your program catch them and carry on.
1 Exceptions Crash
An unhandled error, like 5 / 0, stops the program with a red traceback.
2 try Wraps Risk
Put the risky lines inside try: — Python jumps out at the first failure.
3 except Catches
A matching except block runs instead of a crash, and the program continues.
4 finally Always Runs
The finally block executes whether or not an error happened — perfect for cleanup.
When things go wrong
Exceptions Crash1An unhandled error, like 5 / 0, stops the program with a red traceback. try Wraps Risk2Put the risky lines inside try: — Python jumps out at the first failure. except Catches3A matching except block runs instead of a crash, and the program continues. finally Always Runs4The finally block executes whether or not an error happened — perfect for cleanup. 4 building blocks make up When things go wrong
The try block is a safety zone: an error diverts the flow into the matching handler.
process decision input / output start / end Two accidents, two recoveries — watch execution jump into the handler and then keep going.
mainnums has three elements — the valid indexes are 0, 1 and 2.
Console
output appears as the program runs…
Click an error name, then click the mistake that raises it.
5 conceptsTap a card to expand ?ZeroDivisionErrordrops into place
?IndexErrordrops into place
?KeyErrordrops into place
?ValueErrordrops into place
?finallydrops into place
This try block contains no bug at all — trace what runs and what never does.
Your predicted output — one line per console line
Hint: int("12") succeeds, so the except block never runs — but finally always does.
01try wraps the risky code; except catches the error type you name.
02The first failing line abandons the rest of the try body.
03finally runs every time — error or not — making it ideal for cleanup.
04IndexError, KeyError, ValueError and ZeroDivisionError each name their own cause.
05Read tracebacks bottom-up: the last line names the error and where it hit.