Handle an expected runtime problem, then continue the program.
You already know operations that can succeed or fail. int("42") works, while int("abc") cannot turn that text into an integer. Likewise, 10 / 2 works, but 10 / 0 causes a problem while the program runs. Use try and except when the program expects and knows how to handle a particular runtime problem.
value = "abc"
try:
number = int(value)
print(number)
except ValueError:
print("Please enter a valid number.")Python enters try and attempts int(value). Here int("abc") raises ValueError, so Python skips the remaining lines in that try block, finds the matching except ValueError, and runs its message. Code after the whole try/except structure can then continue.
Please enter a valid number.Keep syntax errors separate from runtime exceptions. A syntax error means Python cannot read the written code correctly, such as print("Hello" with a missing parenthesis. An exception happens while syntactically valid code runs, such as int("abc"). try/except handles expected runtime exceptions; it does not repair invalid Python syntax.
Use this error-handling mental model: risky operation → exception happens → matching except handles it → program continues
value = "12"
try:
number = int(value)
print(number)
except ValueError:
print("Please enter a valid number.")
print("Program continues.")int("12") succeeds, so the rest of try runs and prints 12. No ValueError happens, so that except block is skipped. Python then reaches print("Program continues."). An except block does not run every time; it runs only when its matching exception happens.
int("42")
int("abc")Both inputs are strings, but "42" can become an integer and "abc" cannot. For this lesson, read ValueError as a useful signal that a value cannot be processed in the requested way.
number = 10
try:
print(number / 0)
except ZeroDivisionError:
print("Cannot divide by zero.")Dividing by zero raises ZeroDivisionError, not ValueError. Different expected problems have different exception types, so choose the handler that matches the operation you are protecting.
value = "5"
try:
number = int(value)
print(10 / number)
except ValueError:
print("Please enter a number.")
except ZeroDivisionError:
print("Cannot divide by zero.")With "5", conversion and division succeed, so neither handler runs. With "abc", conversion raises ValueError. With "0", conversion succeeds but division raises ZeroDivisionError. Python chooses the matching except branch for the problem that happened.
value = "0"
try:
number = int(value)
result = 10 / number
print(result)
except ValueError:
print("Invalid number.")
except ZeroDivisionError:
print("Cannot divide by zero.")
print("Done.")Trace it: int("0") returns 0, then 10 / 0 raises ZeroDivisionError. Python skips print(result), runs the matching handler, prints "Cannot divide by zero.", and then continues after the structure to print "Done.".
except ValueError:
print("Please enter a valid number.")A specific handler documents what the program expects and how it will respond. Catching everything without knowing why can hide a different unexpected problem, so begin with the concrete errors your code can handle meaningfully.
A practical error-handling reading checklist
- Find the risky operationWhich operation in
trymight fail while it runs? - Identify the expected exceptionWould this operation cause
ValueError,ZeroDivisionError, or neither? - Trace the try blockWhich lines run successfully before an exception, if one occurs?
- Find the matching exceptWhich
excepthandler matches the exception that happened? - Skip the rest of try after an exceptionAfter an exception, Python leaves the remaining statements in that
tryblock. - Continue after try/exceptWhat code runs next after a matching handler has finished, or after no exception happened?
Common beginner mistakes
- Thinking except always runsAn
exceptblock runs only when its matching exception happens. - Expecting try/except to fix syntax errorsPython syntax must be valid before runtime error handling can run.
- Catching the wrong exception type
ValueErrordoes not handleZeroDivisionError; match the handler to the expected problem. - Expecting the next line inside try to run after an exceptionOnce an exception happens, Python skips the remaining statements in that
tryblock. - Catching everything without knowing whyPrefer specific expected errors that the program can handle clearly.
- Forgetting that execution can continue afterwardAfter a matching handler finishes, code after the
try/exceptstructure can still run.
