Custom Exception Class in C++
Creating Custom Exception Classes in C++.
IntermediateException Handling ProgramsExample 3 of 5
custom-exception-class.cpp
1#include <iostream>2#include <exception>3#include <string>4using namespace std;56// Custom exception class7class MyException : public exception {8private:9 string message;1011public:12 MyException(const string& msg) : message(msg) {}1314 const char* what() const noexcept override {15 return message.c_str();16 }17};1819class AgeException : public exception {20private:21 int age;2223public:24 AgeException(int a) : age(a) {}2526 const char* what() const noexcept override {27 if (age < 0) {28 return "Age cannot be negative";29 } else if (age > 150) {30 return "Age is unrealistic";31 }32 return "Invalid age";33 }3435 int getAge() const { return age; }36};3738void checkAge(int age) {39 if (age < 0 || age > 150) {40 throw AgeException(age);41 }42 cout << "Valid age: " << age << endl;43}4445int main() {46 try {47 checkAge(25);48 checkAge(-5);49 } catch (const AgeException& e) {50 cout << "AgeException caught: " << e.what() << endl;51 }5253 try {54 throw MyException("This is a custom exception");55 } catch (const MyException& e) {56 cout << "\nCustom exception: " << e.what() << endl;57 }5859 return 0;60}
Output
Valid age: 25 AgeException caught: Age cannot be negative Custom exception: This is a custom exception
What's going on
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.
Header Files Used
1.#include <iostream>
Provides cout and cin for input/output operations.
2.#include <exception>
Provides base exception class.
3.#include <string>
Provides string class for error messages.
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
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 {
}
};
1return message.c_str();
How it works
:
Inherit from exception
Store error message
Override what() method
Return error description
Overriding what() Method
Implementation
:
const char* what() const noexcept override {
}
1return message.c_str();
How it works
:
Returns error message
noexcept: doesn't throw
const: doesn't modify
override: ensures override
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 {
}
int getAge() const { return age; }
};
1// Return message based on age
How it works
:
Stores additional data
Custom error logic
Accessor methods
Rich error information
Using Custom Exceptions
Throwing Custom Exception
:
if (age < 0 || age > 150) {
throw AgeException(age);
}
Catching Custom Exception
:
catch (const AgeException& e) {
}
1cout << "AgeException: " << e.what() << endl;2cout << "Age value: " << e.getAge() << endl;
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
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
return 0;
This ends the program successfully.