Understand the idea
A problem you can recognise
A user enters "tomorrow" where the planner expects a number. The program should not pretend that this means zero, and it should not need to abandon every other valid part of the task. An exception lets a failed operation report that it could not deliver its promised result.
The real design question is what the surrounding program can honestly do next: request corrected input, skip a permitted optional operation, or stop with a clear explanation.
Understand the idea
Understand the idea
An exception signals that an operation could not complete normally. It interrupts the current path until an appropriate handler is found. A syntax error in your program and a ValueError while parsing external text are different problems; do not treat every failure as something to ignore and continue past.
A try suite contains the operation that may fail. An except clause handles a specified exception class. Keep the protected operation small enough that the handler’s meaning stays clear. Catching Exception around the whole program can conceal unrelated bugs, such as a misspelled name in the recovery logic. Catch the failures that the program can actually recover from.
The else suite runs if the try suite completes without an exception. finally runs as execution leaves the try statement, whether the operation succeeded or failed. It is useful for cleanup, but a context manager is often clearer for resource management. A recovery value must make sense in the domain: returning zero for invalid exam data can silently convert a bad record into an apparently valid score. Prefer an explicit invalid result when that distinction matters.
See how it works
Example 1: Handle invalid integer text
PYTHON exampleRead the code, then try a change.
Try this example
text = "twelve"
try:
value = int(text)
except ValueError:
print("Enter integer digits")
Expected output:
ReferenceCompare this with the explanation.
Enter integer digits
int cannot parse this word as an integer, so ValueError selects the handler. The program displays an actionable message instead of pretending conversion succeeded.
See how it works
Example 2: Separate success and cleanup
PYTHON exampleRead the code, then try a change.
Try this example
try:
value = int("12")
except ValueError:
print("Invalid")
else:
print(value * 2)
finally:
print("Checked")
Expected output:
ReferenceCompare this with the explanation.
24
Checked
Conversion succeeds, so else runs. finally then runs on exit from the statement. No Invalid message is printed because the except branch was not selected.
Spot the mistake
Example 3: Raise a domain error
PYTHON exampleRead the code, then try a change.
Try this example
def checked_minutes(value):
if value < 0:
raise ValueError("Minutes cannot be negative")
return value
try:
checked_minutes(-5)
except ValueError as error:
print(str(error))
Expected output:
ReferenceCompare this with the explanation.
Minutes cannot be negative
The value is numeric but invalid for the application’s domain. Raising an explicit error distinguishes this situation from a successful duration calculation.
Understand the idea
Think through the important decisions
Trace the try suite until the first failing operation. Statements later in that same suite are skipped when the exception transfers control to a matching handler. The handler is not a request to finish the interrupted operation by guessing a result.
Keep the protected region small enough to identify what can fail. If you put parsing, calculation and unrelated display work into one large try block, an overly broad handler can hide a programming mistake as an input problem. Catch the exception type you expect and keep unrelated defects visible.
Conversion and domain validation remain separate questions. Valid integer syntax can still describe a negative duration your application rejects. A function can deliberately raise a suitable exception when a required rule is broken, allowing its caller to choose an appropriate recovery rather than embedding an unexplained fallback.
Check your understanding
Check the reasoning
Catch a specific expected failure and make recovery explicit rather than hiding unrelated errors.
A matching screenshot or output is one check, not proof that a program is correct for all inputs. Change one input, predict the new result and run again. If the result differs, find the first instruction where your prediction stops matching the program state. Keep that small case as a regression check when you fix the cause.
Spot the mistake
The mistake worth understanding
Catching every exception and continuing with a convenient value can produce a wrong report without any obvious failure. Recovery should preserve the program's meaning, not merely remove an error message. A finally suite is for required cleanup; it is not evidence that the operation succeeded.
Your turn
Independent practice
Write a parser for a positive number of study minutes. Handle nonnumeric text and reject negative values. Test valid text, an invalid word and a negative number without catching every possible exception.
Your turn
Practice hint
Keep int conversion and domain validation visible. Catch ValueError only where recovery is intended.
Your turn
Try a different case
Demonstrate one valid input, invalid numeric text and a parsed value outside the allowed domain. Explain which operation rejects each invalid case and what the caller is allowed to do after that rejection.