52. Safe Sensor Calibration

#include <iostream>
#include <stdexcept>
using namespace std;

void calibrate(int value) {
    if (value < 0) {
        throw invalid_argument("Negative not allowed");
    }
    if (value > 1000) {
        throw runtime_error("Out of range");
    }
    cout << "Calibrated with " << value << "\n";
}

int main() {
    int v;
    cin >> v;

    try {
        calibrate(v);
    } catch (const invalid_argument& e) {
        cout << "Error: " << e.what() << "\n";
    } catch (const runtime_error& e) {
        cout << "Error: " << e.what() << "\n";
    }

    return 0;
}

Solution Details

  • throw invalid_argument("Negative not allowed") for negative input.
     
  • throw runtime_error("Out of range") for values above 1000.
    Multiple catch blocks let us handle each error type separately.
     
  • Correct block is chosen by the exception type.
     

👉 In simple words:

  • If you give a bad calibration value, the function throws an error.
  • Depending on what’s wrong (negative or too big), a different error is caught and printed.
     

Significance for Embedded Developers

  • Firmware often validates inputs like sensor offsets, timer prescalers, buffer sizes.
  • Different types of errors need different handling strategies.

This approach ensures robust and predictable system behavior.
 

Loading...

Input

200

Expected Output

Calibrated with 200