Create a Custom Exception Handler

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.

This is a Challenge, which differs from a Guided Lab in that you need to try to complete the challenge task independently, rather than following the steps of a lab to learn. Challenges are usually a bit difficult. If you find it difficult, you can discuss with Labby or check the solution. Historical data shows that this is a beginner level challenge with a 94% pass rate. It has received a 100% positive review rate from learners.

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.