cpp / beginner
Snippet
Exception Handling with try and catch
Exceptions handle runtime errors gracefully. The throw keyword raises an exception, and catch blocks handle it. Using exceptions instead of error codes makes code cleaner and errors harder to ignore.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <stdexcept>int divide(int a, int b) {if (b == 0) {throw std::invalid_argument("Division by zero!");}return a / b;}try {int result = divide(10, 0);std::cout << result;} catch (const std::invalid_argument& e) {std::cout << "Error: " << e.what();}
Breakdown
1
throw std::invalid_argument("...")
Throws an exception with a message when division by zero occurs
2
catch (const std::invalid_argument& e)
Catches the specific exception type by const reference
3
e.what()
Member function that returns the exception's error message