An example demonstrating how to handle exceptions in C++.
cppCopy code#include <iostream>
#include <stdexcept>
double divide(int a, int b) {
if (b == 0) {
throw std::invalid_argument("Division by zero!");
}
return static_cast<double>(a) / b;
}
int main() {
try {
std::cout << divide(10, 2) << std::endl; // Output: 5
std::cout << divide(10, 0) << std::endl; // This will throw an exception
} catch (const std::invalid_argument& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
return 0;
}
Leave a Reply