Reading Time: 1 minutes
Custom Exception Class in Python
Custom Exception Class for Temperature Control: Write a custom Exception class, derived from the base Exception class, having the following responsibilities. It must take a string argument to display a user-friendly message ("Temperature greater than 400 degrees!!! CODE GREEN! CODE GREEN!") to be displayed when it is raised. It should be raised when the temperature in some system, say, a thermal power plant, crosses 400 degrees Celsius.
Custom Exception Class for Temperature Control
class TemperatureError(Exception): pass myCustomExceptionObject = TemperatureError("Temperature greater than 400 degrees!!! CODE GREEN! CODE GREEN!") def check_temperature(temperature): if temperature > 400: raise myCustomExceptionObject print("Temperature under control.") check_temperature(399) # 'Temperature under control.' check_temperature(450) # amidst stacktrace: 'TemperatureError: Temperature greater than 400 degrees!!! CODE GREEN! CODE GREEN!'