C++ throw Statement
In this page:
The throw Keyword
The throw keyword explicitly raises an exception: the instant a throw statement executes, C++ abandons the normal flow of execution and starts searching up the call stack for the nearest catch block whose type matches what was thrown.
Example: The throw Keyword
#include <iostream>
int main() {
try {
throw 5;
} catch (int e) {
std::cout << "Caught: " << e << std::endl;
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Throwing Different Data Types
You're free to throw primitive values, pointers, strings, or entirely custom types, but throwing a proper exception object — rather than a bare primitive — is the practice most real C++ code follows, since it can carry far more descriptive information about the failure.
Example: Throwing Different Data Types
#include <iostream>
#include <string>
int main() {
try {
throw std::string("Something went wrong");
} catch (std::string &e) {
std::cout << e << std::endl;
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Throwing Objects
Throwing objects is especially useful because the object itself can carry structured details about what went wrong — an error code, a message, related state — giving the code that eventually catches it much more to work with than a bare error number.
Example: Throwing Objects
#include <iostream>
#include <string>
class MyError {
public:
std::string message;
MyError(std::string msg) : message(msg) {}
};
int main() {
try {
throw MyError("Custom error object");
} catch (MyError &e) {
std::cout << e.message << std::endl;
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Rethrowing an Exception
Sometimes a catch block can only partially handle an error and needs to let a higher-level handler deal with the rest; you can rethrow the exception currently being handled simply by writing throw with no operand, which preserves the original exception object.
Example: Rethrowing an Exception
#include <iostream>
void inner() {
try {
throw 42;
} catch (int e) {
std::cout << "Inner partially handles it" << std::endl;
throw;
}
}
int main() {
try {
inner();
} catch (int e) {
std::cout << "Outer fully handles: " << e << std::endl;
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
noexcept Keyword
Declaring a function with the noexcept specifier promises callers it will never throw an exception. If a noexcept function breaks that promise and throws anyway, the runtime immediately calls std::terminate, which ends the program rather than trying to unwind the stack.
Example: noexcept Keyword
#include <iostream>
void safeFunction() noexcept {
std::cout << "Promises never to throw" << std::endl;
}
int main() {
safeFunction();
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: