#include <iostream>
#include <exception>
#include <string>
using namespace std;
// Custom exception class
class MyException : public exception {
private:
string message;
public:
MyException(const string& msg) : message(msg) {}
const char* what() const noexcept override {
return message.c_str();
}
};
class AgeException : public exception {
private:
int age;
public:
AgeException(int a) : age(a) {}
const char* what() const noexcept override {
if (age < 0) {
return "Age cannot be negative";
} else if (age > 150) {
return "Age is unrealistic";
}
return "Invalid age";
}
int getAge() const { return age; }
};
void checkAge(int age) {
if (age < 0 || age > 150) {
throw AgeException(age);
}
cout << "Valid age: " << age << endl;
}
int main() {
try {
checkAge(25);
checkAge(-5);
} catch (const AgeException& e) {
cout << "AgeException caught: " << e.what() << endl;
}
try {
throw MyException("This is a custom exception");
} catch (const MyException& e) {
cout << "\nCustom exception: " << e.what() << endl;
}
return 0;
}Output
Valid age: 25 AgeException caught: Age cannot be negative Custom exception: This is a custom exception
This program teaches you how to create Custom Exception Classes in C++. Custom exceptions allow you to define domain-specific error types with custom data and behavior. They provide more meaningful error information than standard exceptions.
1. What This Program Does
The program demonstrates custom exception classes:
- Creating custom exception classes
- Inheriting from exception class
- Overriding what() method
- Adding custom data members
- Using custom exceptions
Custom exceptions enable domain-specific error handling.
2. Header Files Used
-
#include <iostream>
- Provides cout and cin for input/output operations.
-
#include <exception>
- Provides base exception class.
-
#include <string>
- Provides string class for error messages.
3. Understanding Custom Exceptions
Custom Exception Concept:
- User-defined exception classes
- Inherit from exception
- Add custom data and methods
- Domain-specific errors
Benefits:
- Meaningful error types
- Custom error information
- Better error handling
- Clear error semantics
4. Creating Custom Exception
Basic Structure:
class MyException : public exception { private: string message; public: MyException(const string& msg) : message(msg) {} const char* what() const noexcept override { return message.c_str(); } };
How it works:
- Inherit from exception
- Store error message
- Override what() method
- Return error description
5. Overriding what() Method
Implementation:
const char* what() const noexcept override { return message.c_str(); }
How it works:
- Returns error message
- noexcept: doesn't throw
- const: doesn't modify
- override: ensures override
6. Custom Exception with Data
Adding Data Members:
class AgeException : public exception { private: int age; public: AgeException(int a) : age(a) {} const char* what() const noexcept override { // Return message based on age } int getAge() const { return age; } };
How it works:
- Stores additional data
- Custom error logic
- Accessor methods
- Rich error information
7. Using Custom Exceptions
Throwing Custom Exception:
if (age < 0 || age > 150) { throw AgeException(age); }
Catching Custom Exception:
catch (const AgeException& e) { cout << "AgeException: " << e.what() << endl; cout << "Age value: " << e.getAge() << endl; }
8. When to Use Custom Exceptions
Best For:
- Domain-specific errors
- Custom error information
- Application-specific errors
- Rich error context
- Better error semantics
Example Scenarios:
- Age validation
- Business logic errors
- Application-specific errors
- Custom error types
- Enhanced error information
9. Important Considerations
Inheritance:
- Must inherit from exception
- Override what() method
- Use noexcept for what()
- Follow exception interface
RAII Principles:
- Manage resources properly
- No memory leaks
- Exception-safe
- Clean up resources
Error Messages:
- Provide clear messages
- Help with debugging
- Inform users
- Guide error resolution
10. return 0;
This ends the program successfully.
Summary
- Custom exceptions: inherit from exception class, override what() method.
- Use noexcept for what() method, add custom data members and methods.
- Enable domain-specific error handling with rich error information.
- Follow RAII principles, provide clear error messages.
- Understanding custom exceptions enables meaningful error types.
- Essential for application-specific error handling and better error semantics.
This program is fundamental for learning advanced exception design, understanding custom error types, and preparing for domain-specific error handling in C++ programs.