Open In App

How to Throw a Custom Exception in C++?

Last Updated : 08 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, exception handling is done by throwing an exception in a try block and catching it in the catch block. We generally throw the built-in exceptions provided in the <exception> header but we can also create our own custom exceptions.

In this article, we will discuss how to throw a custom exception in C++.

Throwing Custom Exceptions in C++

To throw a custom exception, we first have to create a custom exception class. This class inherits the std::exception class from <exception> header. We override the what() method of this class to provide a custom error message.

The last step is to use this user-defined custom exception in our code. The below method demonstrates how to do it.

C++ Program to Throw a Custom Exception

C++




// C++ program to demonstrate a custom exception class
  
#include <exception>
#include <iostream>
#include <string>
  
using namespace std;
  
// Define a new exception class that inherits from
// std::exception
class MyException : public exception {
private:
    string message;
  
public:
    // Constructor accepts a const char* that is used to set
    // the exception message
    MyException(const char* msg)
        : message(msg)
    {
    }
  
    // Override the what() method to return our message
    const char* what() const throw()
    {
        return message.c_str();
    }
};
  
// Usage
int main()
{
    try {
        // Throw our custom exception
        throw MyException("This is a custom exception");
    }
    catch (MyException& e) {
        // Catch and handle our custom exception
        cout << "Caught an exception: " << e.what() << endl;
    }
  
    return 0;
}


Output

Caught an exception: This is a custom exception

Related Articles:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads