Custom Exception Class

Creating Custom Exception Classes in C++

IntermediateTopic: Exception Handling Programs
Back

C++ Custom Exception Class Program

This program helps you to learn the fundamental structure and syntax of C++ programming.

Try This Code
#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

Understanding Custom Exception Class

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

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.

---

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 {

}

int getAge() const { return age; }

};

        // Return message based on 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.

Let us now understand every line and the components of the above program.

Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.

Practical Learning Notes for Custom Exception Class

This C++ program is part of the "Exception Handling Programs" topic and is designed to help you build real problem-solving confidence, not just memorize syntax. Start by understanding the goal of the program in plain language, then trace the logic line by line with a custom input of your own. Once you can predict the output before running the code, your understanding becomes much stronger.

A reliable practice pattern is to run the original version first, then modify only one condition or variable at a time. Observe how that single change affects control flow and output. This deliberate style helps you understand loops, conditions, and data movement much faster than copying full solutions repeatedly.

For interview preparation, explain this solution in three layers: the high-level approach, the step-by-step execution, and the time-space tradeoff. If you can teach these three layers clearly, you are ready to solve close variations of this problem under time pressure.

Table of Contents