Topic 72 of 83
std::exception
Overview
Instead of throwing raw integers or strings, C++ provides a standard library of exception classes (`<stdexcept>`). All of them inherit from `std::exception`.
Syntax
cpp
#include <stdexcept>
try {
throw std::invalid_argument("Input cannot be negative");
}
// Catching by reference to avoid copying
catch (const std::exception& e) {
// e.what() returns the error message
std::cout << "Error: " << e.what() << std::endl;
}Common Pitfalls
- Using `v[10]` instead of `v.at(10)`. The `[]` operator does not check bounds and will NOT throw an exception, resulting in silent memory corruption.
Interview Tips
- Always catch exceptions by `const reference` (const std::exception&). If you catch by value, you suffer from 'Object Slicing', where derived exception data is lost.
Real-World Example
Using standard out_of_range exception with vectors.
example
cpp
#include <iostream>
#include <vector>
#include <stdexcept>
using namespace std;
int main() {
vector<int> v = {1, 2, 3};
try {
// v.at() performs bounds checking and throws out_of_range
cout << v.at(10) << endl;
}
catch (const std::out_of_range& e) {
cout << "Bounds Error: " << e.what() << endl;
}
catch (const std::exception& e) {
cout << "Generic Error: " << e.what() << endl;
}
return 0;
}