Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Custom Exception Class in C++

Create a custom exception class in C++ by deriving from std::exception and overriding what(). Includes an AgeException that carries the bad value to the handler.

IntermediateException Handling ProgramsExample 3 of 5
custom-exception-class.cpp
1#include <iostream>
2#include <exception>
3#include <string>
4using namespace std;
5
6// Custom exception class
7class MyException : public exception {
8private:
9 string message;
10
11public:
12 MyException(const string& msg) : message(msg) {}
13
14 const char* what() const noexcept override {
15 return message.c_str();
16 }
17};
18
19class AgeException : public exception {
20private:
21 int age;
22
23public:
24 AgeException(int a) : age(a) {}
25
26 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 }
34
35 int getAge() const { return age; }
36};
37
38void checkAge(int age) {
39 if (age < 0 || age > 150) {
40 throw AgeException(age);
41 }
42 cout << "Valid age: " << age << endl;
43}
44
45int main() {
46 try {
47 checkAge(25);
48 checkAge(-5);
49 } catch (const AgeException& e) {
50 cout << "AgeException caught: " << e.what() << endl;
51 }
52
53 try {
54 throw MyException("This is a custom exception");
55 } catch (const MyException& e) {
56 cout << "\nCustom exception: " << e.what() << endl;
57 }
58
59 return 0;
60}

Sample Output

AgeException caught: Age cannot be negative

checkAge(-5) threw.

Custom exception: This is a custom exception

Thrown and caught directly.

In this one

  • How to derive from std::exception
  • Why what() is const noexcept override
  • How to carry extra data in an exception
  • How a base-class catch still finds the right what()

How it works

  1. 1

    Define MyException with a stored message.

  2. 2

    Define AgeException that stores the age.

  3. 3

    checkAge(25) prints Valid age: 25.

  4. 4

    checkAge(-5) throws; the catch prints the message.

  5. 5

    Throw and catch MyException.

Edge cases

Returning a temporary string

Return (string("Age: ") + to_string(age)).c_str() from what().

The temporary string dies at the end of the return, so the pointer dangles. Store the text in a member instead.

Age over 150

checkAge(200)

what() returns "Age is unrealistic".

Catching by base class

Replace both handlers with catch (const exception& e).

They still work, and what() prints the custom text because it is virtual.

What's going on

The standard exceptions cover common cases, but your own errors often deserve their own type. A custom exception is a class that derives from std::exception and overrides what() to return a message.

MyException stores a string message and returns message.c_str() from what(). Storing the string inside the object matters: the returned pointer stays valid for as long as the exception object exists.

The signature const char* what() const noexcept override has three parts worth reading. const means it does not change the object. noexcept promises it will not throw, which matches the base class and matters because what() is often called while another error is being handled. override asks the compiler to check that it really overrides the base version.

AgeException stores the bad age instead of a message and builds the text in what(), choosing between "Age cannot be negative" and "Age is unrealistic". It also offers getAge(), so a handler can read the actual value. That extra data is the main reason to write your own exception types.

In main, checkAge(25) prints "Valid age: 25". checkAge(-5) throws AgeException(-5), and the catch prints its message. Note that anything after checkAge(-5) in that try block would be skipped.

The second try throws MyException directly and catches it by type.

Because both classes derive from std::exception, a single catch (const exception& e) would also catch them, and e.what() would still call the right override thanks to virtual dispatch.

The headers come first. <iostream> is there because it provides cout and cin for input/output operations. <exception> is there because it provides base exception class. <string> is there because it provides string class for error messages. Leave one out and the compiler stops at the first name it does not recognize.

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 {

return message.c_str();

}

};

What happens here:

Inherit from exception
Store error message
Override what() method
Return error description

Overriding what() Method

Implementation:

const char* what() const noexcept override {

return message.c_str();

}

What happens here:

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 {

// Return message based on age

}

int getAge() const { return age; }

};

What happens here:

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) {

cout << "AgeException: " << e.what() << endl;

cout << "Age value: " << e.getAge() << endl;

}

When to Use Custom Exceptions

Good fits:

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;

return 0; closes main and tells the operating system the program finished without an error.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Why does MyException store a string member?

Pick an answer to check it.

Question 2

What does catch (const exception& e) print for AgeException(-5)?

Pick an answer to check it.

Questions people ask

Should I derive from exception or runtime_error?

runtime_error is easier: class MyException : public runtime_error { using runtime_error::runtime_error; }; gives you message storage for free.

Why noexcept on what()?

The base class declares it that way, and an override cannot throw more than the base allows.

Can an exception carry several values?

Yes. Add any members and getters you want.