1. The Complete Exception Handling Block
try, except, else, finally
- `try`: Encloses code that might raise an exception.
- `except SpecificError as e`: Catches and handles the specified exception.
- `else`: Executes ONLY if the try block ran successfully WITHOUT any exceptions.
- `finally`: Guaranteed to execute under all circumstances, even if an unhandled exception occurred or a return statement was encountered.
def read_number(prompt_val):
try:
num = float(prompt_val)
except ValueError as e:
print("Conversion failed:", e)
return None
else:
print("Successfully parsed:", num)
return num
finally:
print("Cleanup completed.")
read_number("42.5")
read_number("not_a_number")
💡 Key Takeaway: Use `else` for code that should only run on success, and `finally` for resource cleanup.