Introduction
Exception handling helps your program deal with unexpected problems without crashing. It lets you catch errors and fix them or show a friendly message.
Exception handling helps your program deal with unexpected problems without crashing. It lets you catch errors and fix them or show a friendly message.
try { // code that might cause an error } catch (const std::exception& e) { // code to handle the error }
try to wrap code that might fail.catch to handle the error and keep the program running.try { std::stoi("abc"); } catch (const std::exception& e) { std::cout << "Error: " << e.what() << std::endl; }
try { throw std::runtime_error("Something went wrong"); } catch (const std::runtime_error& e) { std::cout << e.what() << std::endl; }
This program tries to divide by zero. Instead of crashing, it catches the error and prints a message. Then it continues running.
#include <iostream> #include <stdexcept> int main() { try { int x = 10; int y = 0; if (y == 0) { throw std::runtime_error("Division by zero is not allowed"); } int z = x / y; std::cout << "Result: " << z << std::endl; } catch (const std::runtime_error& e) { std::cout << "Caught an error: " << e.what() << std::endl; } std::cout << "Program continues after handling the error." << std::endl; return 0; }
Without exception handling, the program would stop immediately on errors.
Exception handling makes programs more reliable and user-friendly.
Exception handling helps catch and manage errors gracefully.
It prevents program crashes and allows recovery or user messages.
Use try and catch blocks to handle exceptions.
try to start a block where exceptions might occur, and catch to handle them.try.try {
throw 10;
std::cout << "No Exception";
} catch (int e) {
std::cout << "Exception caught: " << e;
}throw 10;.try {
int x = 5 / 0;
} catch (int e) {
std::cout << "Error: " << e;
}std::exception or related exceptions allows handling errors without crashing.Pass the test and this pattern moves unknown