try/catch
- C++ course
- Beginner
- Lesson 100/116
- 5 min
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.
Practice 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;.
Starter code
#include <iostream>
#include <string>
// add the stdexcept header
using namespace std;
int main() {
// use try to call stoi, catch the error and print
return 0;
}Sample 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;
}Expected output
Error
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What happens when an exception is thrown in the try block?
- The catch block runs Correct answer
- The program crashes
- The try block continues
- It is a compile error
Explanation: When an exception is thrown, the try block is interrupted and catch runs.
2 Fill in the blank: catch block
try {
throw std::runtime_error("x");
}
____ (const std::exception& e) {
cout << e.what();
}
try {
throw std::runtime_error("x");
}
catch (const std::exception& e) {
cout << e.what();
}
Explanation: The catch keyword catches the exception.
3 Match each block with its job
| Term | Meaning |
|---|---|
try |
risky code |
catch |
catches the error |
throw |
throws an exception |