C++ Custom Exception

In C++, a custom exception is a user-defined class that extends the built-in exception class (or its derived classes) to represent specific types of errors or issues that are specific to your application. By creating custom exceptions, you can throw and catch errors more meaningfully, providing more control over error handling.

How to Define a Custom Exception

1. Create a Class: Define your custom exception class that inherits from exception or another exception type.

2. Override the what() Method: This method returns a string describing the exception when it’s caught.

Example:


#include <iostream>
#include <exception> // For std::exception
using namespace std;

// Step 1: Define a custom exception class
class NegativeAgeException : public exception {
public:
    // Step 2: Override the what() method to return a custom error message
    const char* what() const noexcept override {
        return "Age cannot be negative!";
    }
};

int main() {
    int age = -10;

    try {
        if (age < 0) {
            // Step 3: Throw the custom exception if age is negative
            throw NegativeAgeException();
        }
        cout << "Your age is positive!" << endl;

    } catch (const NegativeAgeException& e) {
        // Step 4: Catching the custom exception and displaying the error message
        cout << "Error: " << e.what() << endl;
    }

    return 0;
}

Explanations:

1. Create a Custom Exception Class (NegativeAgeException):

  1. This class inherits from exception.
  2. The what() method is overridden to return a custom message: "Age cannot be negative!".

2. Throw the Custom Exception:

  • Inside the main() function, the custom exception is thrown when the age is negative.

3. Catch the Custom Exception:

  • The catch block catches the NegativeAgeException and displays the custom error message.

Output:

Error: Age cannot be negative!

C++ Custom Exception – Interview Questions

Q 1: What is a custom exception?
Ans: User-defined exception class.
Q 2: How is custom exception created?
Ans: By inheriting from exception class.
Q 3: Which function is overridden?
Ans: what().
Q 4: Why use custom exceptions?
Ans: To handle application-specific errors.
Q 5: To handle application-specific errors.
Ans: Yes.

C++ Custom Exception – Objective Questions (MCQs)

Q1. How can a user define a custom exception in C++?






Q2. Which function of std::exception class can be overridden to provide custom error messages?






Q3. What is the return type of the what() function in a custom exception class?






Q4. Which header file is required for using std::exception in C++?






Q5. What is the correct syntax to throw a custom exception object named MyException?






Related C++ Custom Exception Topics