Module 4 · Exceptions · Lesson 2 of 6
try and except
The tool for catching errors is the try/except statement. You put the risky code in the try block, and the rescue plan in the except block. If the try code raises an error, Python doesn't crash — it jumps to the handler.
try:n = int(input())print(1 / n)except ZeroDivisionError:print("can't divide by zero")print("done")↳
Follow the flow above. The try block runs normally — until a line raises an exception. At that instant the rest of the try block is skipped, control leaps to the matching except, the handler runs, and then the program carries on below as if nothing had happened.
Two things worth fixing in your mind: the except block runs only when an error was raised — on a good run it's skipped entirely — and either way, execution resumes after the whole statement. No more abrupt crash, no more cryptic traceback for your user.
But is ValueError the only thing that could go wrong here? Enter 0 and find out — which leads straight to the next lesson.