C++ try-catch
In this page:
What is try-catch?
Unexpected problems like invalid user input can otherwise crash a program outright; C++'s try-catch blocks let you handle those situations gracefully instead. You place the risky code inside the try block and write the recovery logic inside the matching catch block.
Example: What is try-catch?
#include <iostream>
int main() {
try {
throw 1;
} catch (int e) {
std::cout << "Handled gracefully" << std::endl;
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Throwing and Catching Integers
C++ actually lets you throw almost any value, and throwing a plain integer is one of the simplest ways to signal an error code. The catch block that receives it behaves much like a function parameter, capturing whatever value was thrown.
Example: Throwing and Catching Integers
#include <iostream>
int main() {
try {
throw 404;
} catch (int errorCode) {
std::cout << "Error code: " << errorCode << std::endl;
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Catching Standard Exceptions
The standard header <stdexcept> is filled with ready-to-use exception classes that all inherit from std::exception and expose a handy what() method returning a human-readable description of what went wrong.
Example: Catching Standard Exceptions
#include <iostream>
#include <stdexcept>
int main() {
try {
throw std::runtime_error("Failure");
} catch (std::exception &e) {
std::cout << e.what() << std::endl;
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Multiple Catch Blocks
A single try block can be followed by several catch blocks, and C++ matches the thrown exception against each one's declared type in order, executing only the first one that matches and skipping the rest entirely.
Example: Multiple Catch Blocks
#include <iostream>
int main() {
try {
throw 3.14;
} catch (int e) {
std::cout << "int" << std::endl;
} catch (double e) {
std::cout << "double: " << e << std::endl;
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
The Catch-All Block
A catch-all block, written using three dots (...) instead of a specific type, catches any exception type that wasn't already handled by an earlier, more specific catch block, acting as a last line of defense so an unexpected error type doesn't crash the program.
Example: The Catch-All Block
#include <iostream>
int main() {
try {
throw 'x';
} catch (int e) {
std::cout << "int" << std::endl;
} catch (...) {
std::cout << "Caught by fallback" << 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: