Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 7.1 — Exceptions: try, except, else, finally
Python · Example 3 of 4

Order of handlers matters

Python runs the first handler that matches. Try swapping the two except blocks to see the specific one never run.

An exception is Python's way of saying that something went wrong at this exact line. try/except lets you catch a specific kind of failure and carry on, else runs only when nothing failed, and finally always runs for cleanup.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 7 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write safe_int(text, default=0) that returns int(text), or default if the text is not a whole number. Test it with "12", "x" and "".

02

Write average(numbers) that returns the average of a list, or None for an empty list. Use try/except ZeroDivisionError.

03

Write a loop over ["3", "0", "x", "5"] that prints 10 / int(item) for each, printing a different friendly message for ZeroDivisionError and for ValueError.

Explain it without notes

01

What happens, step by step, when an exception is raised and no handler is found in the current function?

02

Why is a bare except: considered bad practice, and what should you do instead?

03

What do else and finally do in a try statement, and why is else not just 'code after the try'?

04

What are EAFP and LBYL? When would you pick each?

Order of handlers matters
Sign in to run this example in your browser.

Expected output

4 -> 25.0
0 -> cannot divide by zero
'x' -> needs a number
None -> needs a number