C++ Exception Handling Introduction
In this page:
The try-catch Block
Exception handling gives you a structured way to deal with runtime errors without crashing the whole program: you wrap statements that might fail inside a try block, and any exception they throw gets caught and handled inside a matching catch block.
Example: The try-catch Block
#include <iostream>
int main() {
try {
throw 42;
} catch (int e) {
std::cout << "Caught: " << e << std::endl;
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Throwing Exceptions
The throw keyword is how you signal that a runtime error has occurred; the moment it executes, normal program flow stops immediately and control jumps straight to the nearest catch block whose type matches what was thrown.
Example: Throwing Exceptions
#include <iostream>
#include <string>
void checkAge(int age) {
if (age < 0) throw std::string("Invalid age");
}
int main() {
try {
checkAge(-1);
} catch (std::string &e) {
std::cout << e << std::endl;
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Catching Multiple Exception Types
You can write several catch blocks in a row after a single try block, each one matching a different exception type. The compiler runs only the first catch block whose declared type matches the actual thrown exception, skipping the rest.
Example: Catching Multiple Exception Types
#include <iostream>
int main() {
try {
throw 3.14;
} catch (int e) {
std::cout << "int caught" << std::endl;
} catch (double e) {
std::cout << "double caught: " << e << std::endl;
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Standard Exceptions
The standard library provides ready-made exception classes in the stdexcept header, such as runtime_error and out_of_range, which you can throw yourself or catch generically through their common base class, std::exception.
Example: Standard Exceptions
#include <iostream>
#include <stdexcept>
int main() {
try {
throw std::runtime_error("Something failed");
} catch (std::exception &e) {
std::cout << e.what() << std::endl;
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Catch-All Block (...)
A catch-all block, written with three dots (...) as its parameter list instead of a specific type, catches literally any exception that wasn't matched by an earlier, more specific catch block — a useful safety net at the outermost level of a program.
Example: Catch-All Block (...)
#include <iostream>
int main() {
try {
throw 'x';
} catch (int e) {
std::cout << "int" << std::endl;
} catch (...) {
std::cout << "Caught something unexpected" << std::endl;
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 5 topics to unlock
0/5 topics done
Complete these topics first: