C++ throw Keyword
The throw keyword in C++ is used for exception handling. It signals that an error or an unexpected condition has occurred, transferring control from the point of the exception to a catch block where the exception is handled.
The throw statement is typically used in conjunction with try and catch blocks to provide a structured way to handle runtime errors, making programs more robust and reliable.
Syntax
</>
Copy
throw expression;
- expression
- The exception to be thrown. It can be a literal, variable, or object.
- The
throwstatement transfers control to the nearest enclosingcatchblock that matches the exception type. - If no matching
catchblock is found, the program terminates with an unhandled exception. - Exceptions can be any type, but typically
std::exceptionor its derivatives are used for standard error reporting.
Examples
Example 1: Basic Exception Handling
In this example, you will learn how to use throw with a try–catch block to handle a runtime error.
</>
Copy
#include <iostream>
using namespace std;
int divide(int a, int b) {
if (b == 0) {
throw "Division by zero error"; // Throw a string exception
}
return a / b;
}
int main() {
try {
cout << "Result: " << divide(10, 0) << endl;
} catch (const char* e) {
cout << "Caught exception: " << e << endl;
}
return 0;
}
Output:
Result: Caught exception: Division by zero error
Explanation:
- The
dividefunction checks if the divisor is zero and throws an exception if it is. - The
tryblock callsdivide, and thethrowtransfers control to thecatchblock. - The
catchblock matches the thrown exception type (const char*) and handles the error by printing a message.
Example 2: Throwing and Catching Objects
This example demonstrates how to throw and catch a user-defined exception class.
</>
Copy
#include <iostream>
#include <string>
using namespace std;
class DivisionError {
public:
string message;
DivisionError(string msg) : message(msg) {}
};
int divide(int a, int b) {
if (b == 0) {
throw DivisionError("Division by zero is not allowed");
}
return a / b;
}
int main() {
try {
cout << "Result: " << divide(10, 0) << endl;
} catch (const DivisionError& e) {
cout << "Caught exception: " << e.message << endl;
}
return 0;
}
Output:
Result: Caught exception: Division by zero is not allowed
Explanation:
- The
DivisionErrorclass represents a custom exception with a message. - The
dividefunction throws an instance ofDivisionErrorif the divisor is zero. - The
catchblock matches exceptions of typeDivisionErrorand handles the error by accessing the exception’smessagemember.
Example 3: Rethrowing Exceptions
This example demonstrates how to rethrow an exception from a catch block.
</>
Copy
#include <iostream>
using namespace std;
void process() {
try {
throw "An error occurred"; // Throw a string exception
} catch (...) {
cout << "Exception caught in process()" << endl;
throw; // Rethrow the exception
}
}
int main() {
try {
process();
} catch (const char* e) {
cout << "Exception re-caught in main(): " << e << endl;
}
return 0;
}
Output:
Exception caught in process()
Exception re-caught in main(): An error occurred
Explanation:
- The
processfunction throws an exception and catches it using a catch-all handler (catch (...)). - The
catchblock inprocessrethrows the exception using a barethrow. - The rethrown exception is caught again in the
mainfunction.
Key Points to Remember about throw Keyword
- The
throwkeyword is used to signal an error or exception. - Thrown exceptions must be caught by a corresponding
catchblock. - Exceptions can be of any type, including primitive types, classes, or objects.
- Rethrowing an exception allows further handling in a different context.
- Unhandled exceptions cause the program to terminate.
