Refactor: Replace Generic with Custom Exceptions
Advanced · Refactor · from Python Custom Exceptions: Build Your Own Error Types
From the lesson: Python Custom Exceptions: Build Your Own Error Types
Imagine your car's dashboard had only one warning light that just said "Problem." Not very helpful, right? You'd want to know: is the engine overheating? Is the oil low? Is a door open? The more specific the warning, the faster you can fix the issue.
Read the lessonThe code below uses generic ValueError for all errors. Refactor it to use custom exceptions.
Create:
GradeError(Exception) - base class, just passInvalidGradeError(GradeError) - accepts grade in __init__, stores as self.grade, message: "Invalid grade: X"InvalidSubjectError(GradeError) - accepts subject in __init__, stores as self.subject, message: "Unknown subject: X"Replace the ValueError raises with the appropriate custom exceptions. Update the except blocks to catch InvalidGradeError and InvalidSubjectError separately.
The output should remain exactly the same.
# Original code - refactor this to use custom exceptions
VALID_SUBJECTS = ["math", "science", "english"]
def add_grade(subject, grade):
if subject not in VALID_SUBJECTS:
raise ValueError(f"Unknown subject: {subject}")
if not isinstance(grade, (int, float)) or grade < 0 or grade > 100:
raise ValueError(f"Invalid grade: {grade}")
print(f"Added grade {grade} for {subject}")
test_data = [("math", 95), ("art", 80), ("science", 150), ("english", 88)]
for subject, grade in test_data:
try:
add_grade(subject, grade)
except ValueError as e:
print(f"Error: {e}")
More Custom Exceptions exercises
- Create a Custom ExceptionBeginner
- Predict the Exception HierarchyBeginner
- Exception with Extra DataIntermediate
- Build a Shopping Cart Exception HierarchyAdvanced
All Python exercises · 50 practice problems · Error Handling quiz