Exception with Extra Data
Intermediate · Write the code · 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 lessonCreate a custom exception called TemperatureError with:
__init__ that accepts temp and unit parametersself.temp and self.unit"Invalid temperature: X Y" to super().__init__() (where X is temp and Y is unit)Then write a function check_water_temp(temp) that:
TemperatureError(temp, "C") with message if temp < 0 or temp > 100"Water is liquid at X C" otherwiseTest with check_water_temp(50), then catch errors from check_water_temp(-10) and print both the error message AND the temp attribute.
# Create TemperatureError class
# Write check_water_temp function
# Test it
More Custom Exceptions exercises
All Python exercises · 50 practice problems · Error Handling quiz