Create a Custom Exception Handler

C++C++Beginner
Practice Now

Introduction

In this challenge, you will develop a robust exception handling system for temperature sensors in scientific research. The goal is to create a custom TemperatureException class that inherits from std::runtime_error and implement a temperature validation function that throws the custom exception for invalid temperature readings.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL cpp(("C++")) -.-> cpp/OOPGroup(["OOP"]) cpp(("C++")) -.-> cpp/AdvancedConceptsGroup(["Advanced Concepts"]) cpp/OOPGroup -.-> cpp/classes_objects("Classes/Objects") cpp/OOPGroup -.-> cpp/inheritance("Inheritance") cpp/AdvancedConceptsGroup -.-> cpp/exceptions("Exceptions") subgraph Lab Skills cpp/classes_objects -.-> lab-446292{{"Create a Custom Exception Handler"}} cpp/inheritance -.-> lab-446292{{"Create a Custom Exception Handler"}} cpp/exceptions -.-> lab-446292{{"Create a Custom Exception Handler"}} end

Create a Temperature Exception Handler

In scientific research, accurate temperature monitoring is crucial. Your task is to develop a robust exception handling system for temperature sensors that can detect and report invalid readings.

Tasks

Complete the following TODOs in the template code:

  1. Implement the TemperatureException constructor:

    • Initialize base class with error message
    • Set the invalid temperature value
  2. Implement the validateTemperature function:

    • Check if temperature is within [-50°C, 100°C]
    • Throw TemperatureException for invalid values

Requirements

  • Temperature range: -50°C to 100°C
  • Error message: "Temperature Error: Invalid temperature reading"
  • Must use provided class structure
  • Do not modify main() function

Examples

COmpile and run the code to test the temperature validation function. The program should throw a TemperatureException for invalid temperature readings.

g++ temperature_exception.cpp -o temperature_exception
./temperature_exception

Valid temperature:

Testing valid temperature:
Temperature 25.0°C is valid.

Invalid temperature:

Temperature Error: Invalid temperature reading
Invalid Temperature: 150°C

Hints

  • Use the constructor of std::runtime_error to set the error message
  • Store the invalid temperature as a private member of the exception class
  • Create a getter method to retrieve the invalid temperature value
✨ Check Solution and Practice

Summary

In summary, this challenge requires you to create a custom TemperatureException class that inherits from std::runtime_error and implement a temperature validation function that throws the custom exception for invalid temperature readings. The goal is to develop a robust exception handling system for temperature sensors in scientific research.