Editor

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 lesson

Create a custom exception called TemperatureError with:

  • An __init__ that accepts temp and unit parameters
  • Stores self.temp and self.unit
  • Passes the message "Invalid temperature: X Y" to super().__init__() (where X is temp and Y is unit)
  • Then write a function check_water_temp(temp) that:

  • Raises TemperatureError(temp, "C") with message if temp < 0 or temp > 100
  • Prints "Water is liquid at X C" otherwise
  • Test 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