C++ throw statement
Created By: chatGPT
C++ provides a throw statement to handle exceptions. When an error occurs in a program, the throw statement allows you to signal an exception, which can then be caught and handled, avoiding program crashes. Here’s a basic illustration of how the throw statement can be used in conjunction with try and catch blocks.
try {
throw std::runtime_error("An error occurred");
} catch (const std::runtime_error& e) {
std::cerr << "Caught: " << e.what() << std::endl;
}
In this example: the try block contains code that may throw an exception. If an exception of type std::runtime_error is thrown, control passes to the catch block where the exception is handled. It is good practice to include error messages to aid debugging.
void riskyFunction() {
if (/* some error condition */) {
throw std::logic_error("Logic error encountered");
}
}
You can also define your own exception classes by inheriting from std::exception. This allows you to provide specific error information and tailor the exception to your application's needs.
class MyException : public std::exception {
public:
const char* what() const noexcept override {
return "My custom exception occurred";
}
};
void anotherRiskyFunction() {
throw MyException();
}
When catching exceptions, it’s important to catch by reference to avoid slicing and unnecessary copies. Use const to prevent modification of the caught exception. Always aim to have catch blocks for more specific exceptions before more general ones.
try {
anotherRiskyFunction();
} catch (const MyException& e) {
std::cerr << "Caught: " << e.what() << std::endl;
} catch (const std::exception& e) {
std::cerr << "Caught a general exception: " << e.what() << std::endl;
}