example1_invalid_arguments.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <stdexcept>
#include <cmath>

double calculateSquareRoot(double number) {
    if (number < 0) {
        throw std::invalid_argument("Negative input is not allowed");
    }
    return std::sqrt(number);
}

int main() {
    try {
        std::cout << calculateSquareRoot(-9) << std::endl;
    } catch (const std::invalid_argument& e) {
        std::cerr << "Error: " << e.what() << std::endl;
    }
    return 0;
}
Back to stdexcept