Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
#include <iostream> #include <stdexcept> #include <string> double safeDivide(double a, double b) { if (b == 0.0) throw std::invalid_argument("Division by zero"); return a / b; } int parseAge(const std::string& s) { int age = std::stoi(s); // throws std::invalid_argument or std::out_of_range if (age < 0 || age > 150) throw std::out_of_range("Age out of plausible range"); return age; } void riskyOperation() { try { double result = safeDivide(10.0, 0.0); std::cout << result << " "; } catch (const std::invalid_argument& e) { std::cout << "Caught invalid_argument: " << e.what() << " "; throw; // rethrow to outer handler } } int main() { // Nested try/catch with rethrow try { riskyOperation(); } catch (const std::exception& e) { std::cout << "Outer handler: " << e.what() << " "; } // Multiple catch handlers, ordered most-derived first try { parseAge("-5"); } catch (const std::out_of_range& e) { std::cout << "Out of range: " << e.what() << " "; } catch (const std::invalid_argument& e) { std::cout << "Invalid argument: " << e.what() << " "; } catch (const std::exception& e) { std::cout << "std::exception: " << e.what() << " "; } catch (...) { std::cout << "Unknown exception "; } return 0; }
Result
Open