In C++, exception handling allows you to catch and handle errors that occur during the execution of a program. While C++ provides built-in exception classes such as std::exception
, you can also create your own custom exception classes to handle specific error scenarios.
Creating custom exception classes allows you to provide more specific information about the error and define custom behavior for handling it. This can be especially useful when you want to differentiate between different types of errors or when you want to add additional properties or methods to your exception class.
To create a custom exception class in C++, you can follow these steps:
- Define a new class that inherits from the
std::exception
class or one of its derived classes. - Implement any additional properties or methods that you want to include in your custom exception class.
- Override the
what()
method to provide a human-readable error message.
Here's an example of creating a custom exception class in C++:
1#include <iostream>
2#include <exception>
3
4class CustomException : public std::exception {
5public:
6 const char* what() const noexcept override {
7 return "This is a custom exception.";
8 }
9};
10
11int main() {
12 try {
13 throw CustomException();
14 }
15 catch (const std::exception& e) {
16 std::cout << "Exception caught: " << e.what() << std::endl;
17 }
18 return 0;
19}
In this example, we define a custom exception class CustomException
that inherits from the std::exception
class. We override the what()
method to provide a custom error message. Inside the main()
function, we throw an instance of CustomException
and catch it using a std::exception
reference. The what()
method is called to retrieve the error message and display it.
By creating custom exception classes, you can have more fine-grained control over the handling of different types of errors in your C++ programs. This can help you handle errors in a more specific and meaningful way, improving the overall quality and maintainability of your code.
xxxxxxxxxx
class CustomException : public std::exception {
public:
const char* what() const noexcept override {
return "This is a custom exception.";
}
};
int main() {
try {
throw CustomException();
}
catch (const std::exception& e) {
std::cout << "Exception caught: " << e.what() << std::endl;
}
return 0;
}