C++ exceptions are a way to handle errors that occur during program execution. They allow you to transfer control from one part of a program to another, and to handle the error in a centralized way.
To use exceptions in C++, you use the following keywords:
The following code shows an example of how to use exceptions:
#include <iostream>
using namespace std;
int main() {
try {
// Code that could potentially throw an exception.
int x = 10 / 0;
} catch (exception& e) {
// Handle the exception.
cout << "Error: " << e.what() << endl;
}
return 0;
}
Output:
Error: division by zero
In this example, the try block contains code that could potentially throw an exception, such as dividing by zero. If an exception is thrown, the catch block will be executed to handle the exception.
You can also throw custom exceptions. To do this, you create a class that inherits from the std::exception class. The following code shows an example of how to create a custom exception:
class MyException : public std::exception {
public:
MyException(const string& message) : message(message) {}
const char* what() const override {
return message.c_str();
}
private:
string message;
};
The following code shows an example of how to throw a custom exception:
#include <iostream>
using namespace std;
int main() {
try {
if (10 < 5) {
throw MyException("10 is not less than 5.");
}
} catch (MyException& e) {
// Handle the custom exception.
cout << "Error: " << e.what() << endl;
}
return 0;
}
Output:
Error: 10 is not less than 5.
Benefits of using exceptions
There are several benefits to using exceptions in C++, including:
Conclusion
Exceptions are a powerful feature of C++ that can be used to write more robust, reliable, and readable code. By understanding how to use exceptions, you can write better C++ code.