Exceptions: Raising, Catching and Recovering
Signalling an unusable input or failed operation with an exception, then choosing a deliberate handling policy. Expected failures may be recovered from; other failures may be reported and propagated rather than silently suppressed.
What a learner can do afterwards
- Catch a specific exception around a risky operation and recover from it
- Raise an exception when a function is given input it cannot work with
- Explain why catching every exception and continuing is usually the wrong repair
1 · Read
Exception types depend on the operation. open('notes.txt', 'r') raises FileNotFoundError if the path is absent. int('leaf') raises ValueError because the text is not an integer. Accessing an out-of-range list position raises IndexError. Opening in 'w' or 'a' can create a missing file instead.
try runs the risky operation. A matching except handles its exception; later lines inside that try are skipped. ```python try: number = int("leaf") print(number) except ValueError: print("Use integer digits") ``` The conversion raises ValueError, so the handler prints its message instead of printing number.
A function can reject input explicitly: ```python def half_positive(n): if n <= 0: raise ValueError("positive required") return n / 2 ``` raise interrupts this call. The caller may handle the exception; the function does not return a made-up numeric result.
Choose a handler from the operation and its failure conditions. Opening an absent path in 'r' raises FileNotFoundError; converting nonnumeric text with int raises ValueError. A missing configuration file might be reported before stopping safely; invalid numeric text might prompt another input request. Other read or conversion failures can have different types. Use a result only after its operation succeeds.
Bare except catches broadly; pass does nothing. Silent continuation can reuse stale data: ```python number = 5 try: number = int("leaf") except: pass print(number) ``` The failed assignment leaves 5 unchanged. A deliberate policy must decide whether continuation is valid.
Broad handling need not suppress a failure: ```python try: operation() except Exception as err: print(err) raise ``` Bare raise propagates the current exception after reporting it. A handler may recover, report and propagate, or stop safely. In a plain script with default reporting, an uncaught exception prints an error and stops the script.
Match the exception to the failed operation. Raise for unusable input. Handle with a deliberate policy: recover, report and propagate, or stop safely.
Exception teaching adapted from the Introduction to Python Programming chapter 14 corpus records, with independently written control-flow examples, handling-policy explanations and assessment repairs.
Readings written for this dataset, with corrections to operation-specific errors and deliberate handling policies.
2 · Watch
به انگلیسیTake it off screen
Where it sits
Learn first
This opens up
8 questions wait behind this lesson, each with its answer explained. Every answer feeds the sky: stars light as they are learned, and dim when it is time to come back.