C++ Exceptions
An exception is a signal that a program throws when something goes wrong. A catch block handles the signal so the program can carry on.
Catching a thrown code
The try block throws the code 404. The catch block prints the code, and the next line shows the program continues.
#include <iostream>
int main() {
try {
throw 404;
} catch (int code) {
std::cout << "Error code: " << code << std::endl;
}
std::cout << "Program continues" << std::endl;
return 0;
}A try block with no error
Nothing is thrown in this try block. Its line prints, and the catch block does not run.
#include <iostream>
int main() {
try {
std::cout << "All is well" << std::endl;
} catch (int code) {
std::cout << "Error code: " << code << std::endl;
}
return 0;
}An uncaught error stops the program
This program has no try block. The at call throws, and the program stops with the line below.
#include <iostream>
#include <vector>
int main() {
std::vector<int> scores = {10, 20, 30};
std::cout << scores.at(5) << std::endl;
return 0;
}Example
#include <iostream>
void checkAge(int age) {
if (age < 18) {
throw 1;
}
std::cout << "Access granted" << std::endl;
}
int main() {
try {
checkAge(15);
} catch (int code) {
std::cout << "Access denied: code " << code << std::endl;
}
try {
checkAge(20);
} catch (int code) {
std::cout << "Access denied: code " << code << std::endl;
}
return 0;
}Key points
- The try keyword marks a block that might throw.
- The throw keyword throws a value as a signal.
- The catch keyword marks a block that handles a thrown value.
- A catch block names the type of value it catches.
- Code after a try and catch pair runs after the catch block finishes.
In this example, checkAge throws the code 1 for the age 15. The first catch block prints the denied line with that code. The second call passes for the age 20 and prints the granted line.
Note
The standard library throws its own exceptions for some errors, such as a failed at call on a vector.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz C++ Compiler
Exercise
What does a catch block do?