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

Custom exception classes inherit from exception class. Override what() method to return error message. Use noexcept for what() method. Custom exceptions allow domain-specific error handling. Can add additional data members and methods. Follow RAII principles in exception classes.

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.

Table of Contents