std::exception
Overview
Throwing raw strings (throw "Error";) or integers (throw 404;) is fine for beginners, but terrible for professional engineering. Raw primitives don't provide Stack Traces or unified interfaces.
The C++ Standard Library provides a built-in Object-Oriented base class called `std::exception` (via the <stdexcept> header). It contains a standardized virtual method called .what() that returns a descriptive string of the error. All standard C++ errors (like out_of_range when messing up a vector, or bad_alloc when running out of RAM) inherit from this base class.
Syntax
#include <iostream>
#include <vector>
#include <stdexcept> // Contains standard exception classes
int main() {
std::vector<int> data = {10, 20};
try {
// .at() is mathematically safe and will actively THROW an
// std::out_of_range exception if the index doesn't exist!
std::cout << data.at(99);
}
// We catch the Base Class (std::exception) by Reference!
// Thanks to Polymorphism, this catches ALL standard errors!
catch (const std::exception& e) {
// e.what() dynamically prints the specific error message
std::cout << "STL Error Intercepted: " << e.what() << "\n";
}
return 0;
}Common Pitfalls
- Catching by Value. If you write
catch (std::exception e), you trigger 'Object Slicing'. If the actual error thrown was a massivestd::out_of_rangechild class, the compiler forcefully slices away all the child data to shrink it into a pure base class, destroying the detailed error message. ALWAYS useconst std::exception& e.
Interview Questions
int* p = new int[999999999999];) fails because the computer is completely out of RAM, what specific Exception is thrown?The new operator throws a std::bad_alloc exception. Because std::bad_alloc inherits from std::exception, catching std::exception will gracefully catch memory exhaustion issues.
Real-World Example
Throwing a standardized STL exception manually to enforce strict architectural rules.
#include <iostream>
#include <stdexcept>
void setAge(int age) {
if (age < 0) {
// Throwing a standard STL 'invalid_argument' object
throw std::invalid_argument("Age cannot be mathematically negative.");
}
std::cout << "Age set to " << age << "\n";
}
int main() {
try {
setAge(-5);
} catch (const std::exception& e) {
// .what() will print our custom message!
std::cout << "[ERROR] " << e.what() << "\n";
}
return 0;
}Check Your Knowledge
Test your understanding of std::exception with these quick questions.