#include <iostream>
#if 0
/*It's worth noting that C++ provides several standard exception classes such as
std::invalid_argument, std::domain_error, std::out_of_range, std::length_error,
std::range_error, std::overflow_error, std::underflow_error, and std::logic_error
which are derived from the std::exception class, these standard exception classes
are commonly used to indicate specific types of errors and help in better
understanding the errors, and make error handling more robust.*/
int add(int a, int b) {
if (b < 0) {
throw "negative number not allowed";
}
return a + b;
}
int diff(int a, int b) {
if(a > b) {
throw "difference is negative";
}
return a - b;
}
int main() {
int a = 5, b = -2;
try {
std::cout << "Result: " << diff(a, b) << std::endl;
} catch (const char* e) {
std::cout << "Error: " << e << std::endl;
}
try {
std::cout << "Result: " << add(a, b) << std::endl;
} catch (const char* e) {
std::cout << "Error: " << e << std::endl;
}
return 0;
}
#endif
#include <stdexcept>
int add(int a, int b) {
if (b < 0) {
throw std::invalid_argument("Negative numbers are not allowed as second argument in add function");
}
return a + b;
}
int diff(int a, int b) {
if(a > b) {
throw std::domain_error("First argument should be less than second argument in diff function");
}
return a - b;
}
int main() {
int a = 5, b = -2;
try {
std::cout << "Result: " << diff(a, b) << std::endl;
std::cout << "Result: " << add(a, b) << std::endl;
} catch (const std::exception& e) {
std::cout << "Error: " << e.what() << std::endl;
}
try {
std::cout << "Result: " << add(a, b) << std::endl;
} catch (const std::exception& e) {
std::cout << "Error: " << e.what() << std::endl;
}
return 0;
}
To embed this project on your website, copy the following code and paste it into your website's HTML: