Error & Exception Handling: try-except-else-finally & Custom Exceptions
1Concept
Python handles exceptions with try, except, else (runs only if NO exception occurred), and finally (ALWAYS runs). Exceptions inherit from Exception. Exception chaining (raise CustomError from err) preserves original tracebacks.
2Architecture Diagram
try:
Attempt dangerous operation
except SpecificError as e:
Handle specific error
else:
Executes ONLY if NO exception was raised
finally:
ALWAYS executes (Cleanup)3Code Example
Stage 0 Language Foundations
class ValidationError(Exception):
# Custom application validation exception
pass
def validate_age(age: int) -> bool:
if not isinstance(age, int):
raise TypeError("Age must be an integer.")
if age < 18 or age > 120:
raise ValidationError(f"Invalid age {age}. Must be between 18 and 120.")
return True
test_inputs = [25, 15, "invalid"]
for val in test_inputs:
try:
validate_age(val) # type: ignore
except ValidationError as ve:
print(f"[Validation Failed] {ve}")
except TypeError as te:
print(f"[Type Error] {te}")
else:
print(f"[Success] Age {val} is verified.")
finally:
print("--- Next Check ---")4Expected Output
[Success] Age 25 is verified. --- Next Check --- [Validation Failed] Invalid age 15. Must be between 18 and 120. --- Next Check --- [Type Error] Age must be an integer. --- Next Check ---
5Key Takeaways
- ✓Use the 'else' block for code that should execute only if the try block succeeded.
- ✓Always catch specific exceptions rather than bare 'except:'.
- ✓Custom exceptions should inherit from Exception, not BaseException.