C++ User-Defined Exceptions
C++ provides the ability to define your own exceptions by creating classes that inherit from the standard exception class. This allows for more specific and targeted error handling.
Syntax
To define a user-defined exception, you need to create a class that inherits from the standard exception class, and define a constructor which takes a string argument.
class MyException : public std::exception {
public:
MyException(const char* message) {
this->message = message;
}
const char* what() const noexcept override {
return message.c_str();
}
private:
std::string message;
};
In the above example, we have defined a custom exception called "MyException" which takes a string message as an argument in its constructor.
Example
#include <iostream>
#include <stdexcept>
class MyException : public std::exception {
public:
MyException(const char* message) {
this->message = message;
}
const char* what() const noexcept override {
return message.c_str();
}
private:
std::string message;
};
int main() {
try {
int age;
std::cout << "Enter your age: ";
std::cin >> age;
if (age < 18) {
throw MyException("Too young!");
}
else {
std::cout << "Welcome!" << std::endl;
}
}
catch (std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
return 0;
}
In the above example, we have defined a custom exception called "MyException" which is thrown when the user enters an age less than 18. The exception message is then displayed to the user.
Output
Enter your age: 16
Error: Too young!
Explanation
In the above example, we prompt the user to enter their age. If their age is less than 18, we throw a custom exception called "MyException" with the message "Too young!".
In the catch block, we catch any exceptions of type "std::exception" and display the exception message to the user.
Use
User-defined exceptions are useful for specific and targeted error handling. They can provide more detailed information about the cause of an exception, which can help with debugging and problem solving.
Important Points
- User-defined exceptions can be created by defining a class that inherits from std::exception and defines a constructor that takes a string message as an argument.
- User-defined exceptions can provide more specific and targeted error handling.
- User-defined exceptions can help with debugging and problem solving by providing more detailed information about the cause of an exception.
Summary
In summary, user-defined exceptions in C++ allow for more specific and targeted error handling by creating custom exception classes that inherit from std::exception. They can provide more detailed information about the cause of an exception, which can help with debugging and problem solving.