Open In App

Polymorphic Exceptions In C++

Last Updated : 25 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

C++ is a powerful programming language that allows developers to handle errors and exceptional situations using exceptions. In this article, we will explore the concept of polymorphic exceptions in C++. Polymorphic exceptions allow you to create custom exception classes that can be caught at different levels of specificity, providing more detailed error information when needed. We’ll learn how to create and use polymorphic exception classes and understand their benefits in improving code clarity and maintainability.

Polymorphism in C++ allows different classes to be treated as objects of a common base class. This concept can be extended to exception handling.

Creating a Polymorphic Exception Class

To create a polymorphic exception class, derive a custom exception class from ‘std::exception’. Override the ‘what()’ function to provide a custom error message.

C++




#include <iostream>
#include <exception>
  
// Define a custom exception class 'MyException'
// It inherits from 'exception'
class MyException : public exception {
public:
      // Constructor for 'MyException'
      // message is taken as parameter
    MyException(const char* message) : message_(message) {}
      
      // Here, we override the 'what' function present in 'exception'
       // This is done to provide a custom error message
    const char* what() const noexcept override {
        return message_.c_str();
    }
  
private:
      // member variable to store error message
    string message_; 
};


Catching Polymorphic Exceptions

Once you’ve created a polymorphic exception class, you can use it like any other exception class.

C++




try {
    // try to throw a custom exception of type MyException.
    throw MyException("Custom exception message");
}
catch (const exception& e) {
    // catching the exception message and printing its
    // custom message.
    cerr << "Exception caught: " << e.what() << endl;
}


The catch block specifies a reference to ‘std::exception’, which can catch exceptions of the custom type or any derived classes.

Example

Here’s a complete example of creating and using a polymorphic exception class:

C++




// C++ Program to illustrate Polymorphic Exceptions
#include <exception>
#include <iostream>
using namespace std;
  
// Define a custom exception class 'MyException'
// It inherits from 'exception'
class MyException : public exception {
public:
    // Constructor for 'MyException'
    // message is taken as parameter
    MyException(const char* message)
        : message_(message){}
  
    // Here, we override the 'what' function present in
    // 'exception' This is done to provide a custom error
    // message
    const char* what() const noexcept override
    {
        return message_.c_str();
    }
  
private:
    // member variable to store error message
    string message_;
};
  
int main()
{
  
    try {
        // try to throw a custom exception of type
        // MyException.
        throw MyException("Custom exception message");
    }
    catch (const exception& e) {
        // catching the exception message and printing its
        // custom message.
        cerr << "Exception caught: " << e.what()
             << endl;
    }
    return 0;
}


Output

Exception caught: Custom exception message

Advantages of Polymorphic Exceptions

Polymorphic Exceptions offer several benefits which are as follows:

  1. Custom Error Messages: You can provide detailed error messages, making it easier to identify and troubleshoot issues.
  2. Flexible Exception Handling: Polymorphic exceptions allow you to catch exceptions at different levels of specificity, enabling more precise error handling.
  3. Code Readability: By using descriptive exception types, your code becomes more self-explanatory and easier for others to understand.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads