std::exception
- C++ course
- Beginner
- Lesson 102/116
- 5 min
Learn std::exception and the what() method.
std::exception base type
std::exception is the base type of C++'s standard exception hierarchy. Types like runtime_error, invalid_argument, out_of_range are all derived from it. This lets a single catch block catch all standard exceptions.
catch (const std::exception& e) {
cout << e.what();
}Here e.what() returns the exception's description string. Catching by base type reference avoids copying and catches derived types without losing their details.
Using the what() method
The what() method returns a string pointer describing the exception's cause. This string is the text given to the exception constructor. It is useful for debugging and user reporting.
try {
throw std::runtime_error("file not found");
} catch (const std::exception& e) {
cout << "Error: " << e.what() << endl;
}Here e.what() becomes "file not found". This pattern is the standard way to tell the user what went wrong.
Practice Print the message with what()
Add #include <stdexcept>. Inside a try block, write throw std::runtime_error("file not found");. In a catch (const std::exception& e) block, print the message with cout << e.what() << endl;.
Starter code
#include <iostream>
#include <stdexcept>
using namespace std;
int main() {
// in try throw, in catch print the message
return 0;
}Sample solution
#include <iostream>
#include <stdexcept>
using namespace std;
int main() {
try {
throw std::runtime_error("file not found");
} catch (const std::exception& e) {
cout << e.what() << endl;
}
return 0;
}Expected output
file not found
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which method of std::exception returns the description string?
- message()
- why()
- what() Correct answer
- text()
Explanation: what() returns the description string.
2 Match each exception type with its scenario
| Term | Meaning |
|---|---|
runtime_error |
runtime error |
invalid_argument |
invalid input |
out_of_range |
out of bounds |
3 Fill in the blank: what() call
try {
throw std::runtime_error("x");
}
catch (const std::exception& e) {
cout << e.____();
}
try {
throw std::runtime_error("x");
}
catch (const std::exception& e) {
cout << e.what();
}
Explanation: e.what() returns the exception message.