C++
try/catch
Learn to catch runtime errors with try/catch.
Catching errors with try/catch
In C++, when a runtime error (exception) occurs, the program normally crashes. To prevent this, you put risky code in a try block and error-handling code in a catch block. When an exception is thrown, the catch block runs and the program continues.
try {
int n = stoi("abc");
} catch (const std::invalid_argument& e) {
cout << "Error";
}
Here stoi("abc") throws an std::invalid_argument; the catch block catches it and the program continues without crashing. The #include <stdexcept> header brings in the exception types.
The catch block and exception type
Each catch block catches a specific exception type. The type is declared in parentheses as a reference: catch (const std::exception& e). This form avoids copying and lets a base type catch derived types.
try {
throw std::runtime_error("wrong");
} catch (const std::exception& e) {
cout << e.what();
}
Here std::runtime_error is derived from std::exception, so it is caught by its catch block. e.what() returns the exception's description string.
Exercise Catch the stoi error
Add the #include <stdexcept> header. Inside a try block, call int n = stoi("abc");. In a catch (const std::invalid_argument& e) block, print cout << "Error" << endl;.
Show example solution
#include <iostream>
#include <string>
#include <stdexcept>
using namespace std;
int main() {
try {
int n = stoi("abc");
} catch (const std::invalid_argument& e) {
cout << "Error" << endl;
}
return 0;
}
Test yourself
-
What happens when an exception is thrown in the try block?
- The catch block runs
- The program crashes
- The try block continues
- It is a compile error
Show answer
The catch block runs — When an exception is thrown, the try block is interrupted and catch runs.
-
Fill in the blank: catch block
try {
throw std::runtime_error("x");
}
____ (const std::exception& e) {
cout << e.what();
}
Show answer
try {
throw std::runtime_error("x");
}
catch (const std::exception& e) {
cout << e.what();
}
-
Match each block with its job
- try
- risky code
- catch
- catches the error
- throw
- throws an exception
Next lesson: throw