cpp / beginner
Snippet
Exception Handling with try and catch
Exception handling prevents program crashes when errors occur. The try block contains code that might throw an exception, and catch blocks handle specific exception types. When an exception is thrown, program execution jumps to the matching catch block. This is cleaner than checking return values for every function call.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>#include <stdexcept>int divide(int a, int b) {if (b == 0) {throw std::runtime_error("Division by zero not allowed");}return a / b;}int main() {try {std::cout << divide(10, 2) << std::endl;std::cout << divide(5, 0) << std::endl;}catch (const std::runtime_error& e) {std::cout << "Error: " << e.what() << std::endl;}std::cout << "Program continues..." << std::endl;return 0;}
Breakdown
1
throw std::runtime_error("...")
Throws an exception with an error message
2
catch (const std::runtime_error& e)
Catches the exception and binds it to reference e
3
e.what()
Returns the error message string from the exception
4
Program continues...
This line executes because the exception was caught