An except block handles an exception raised by the protected try block. When a matching exception occurs, Python skips the remaining try statements, runs the except block, and then continues outside the statement; when no exception occurs, Python skips it. section 12.3.1
Use except blocks to keep failure handling focused and maintainable:
- Put only code that can raise the intended exception in the try block; a narrow protected region makes the failure source easier to identify. section 12.3.1
- Name the exceptions explicitly instead of using a bare except block. section 12.3.1 section 12.6
- Use separate except blocks for unrelated exceptions; group closely related exceptions in a tuple when they share the same response. section 12.3.3 section 12.6
- Return, report, or otherwise finish the error path before code requiring successfully assigned values runs. section 12.4
Handle invalid task urgency
def process_task_string(text): title, urgency_str = text.split(",") try: urgency = int(urgency_str) except ValueError as ex: print(f"Couldn't cast the number. Description: {ex}") return None return Task(title, urgency) process_task_string("Laundry,3#") # output: Couldn't cast the number. Description: invalid literal for int() with base 10: '3#' process_task_string("Laundry,3") # returns: Task(title='Laundry', urgency=3) The successful path skips the except block. The invalid input enters it and returns None, preventing later code from using an unassigned urgency value. section 12.3.1 section 12.4
Figure 12.4 The workflow of a try...except statement. We include the code that potentially raises an exception in the try clause. When such an exception is raised, the except clause gets executed, and execution moves to the code outside the statement. If no exception is raised when the code in the try clause is executed, Python skips the except clause.
Trace the two execution paths: successful try execution skips the except block, while a raised exception transfers control to it and then moves outside the statement. section 12.3.1

