Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C++ Data Types
  • C++ Input/Output
  • C++ Arrays
  • C++ Pointers
  • C++ OOPs
  • C++ STL
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ MCQ
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management
Open In App
Next Article:
Rethrowing an Exception in C++
Next article icon

Polymorphic Exceptions In C++

Last Updated : 25 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
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.

Next Article
Rethrowing an Exception in C++

M

mathpaljyoti8271
Improve
Article Tags :
  • C++
  • Geeks Premier League
  • Geeks Premier League 2023
Practice Tags :
  • CPP

Similar Reads

  • Concrete Exceptions in Python
    In Python, exceptions are a way of handling errors that occur during the execution of the program. When an error occurs Python raises an exception that can be caught and handled by the programmer to prevent the program from crashing. In this article, we will see about concrete exceptions in Python i
    3 min read
  • Rethrowing an Exception in C++
    Exception handling plays a role in developing robust software in C++. It offers a way to handle errors and unexpected situations. One interesting aspect of exception handling in C++ is the ability to rethrow an exception allowing it to pass up the call stack. Rethrowing an ExceptionRethrowing an exc
    5 min read
  • Python Print Exception
    In Python, exceptions are errors that occur at runtime and can crash your program if not handled. While catching exceptions is important, printing them helps us understand what went wrong and where. In this article, we'll focus on different ways to print exceptions. Using as keywordas keyword lets u
    3 min read
  • is_polymorphic template in C++
    The std::is_polymorphic template of C++ STL is used to checks whether the type is a polymorphic class type or not. It returns a boolean value showing the same. Syntax: template < class T > struct is_polymorphic; Parameter: This template contains single parameter T (Trait class) to check whethe
    2 min read
  • Exception Handling in C++
    In C++, exceptions are unexpected problems or errors that occur while a program is running. For example, in a program that divides two numbers, dividing a number by 0 is an exception as it may lead to undefined errors. The process of dealing with exceptions is known as exception handling. It allows
    11 min read
  • Exception Propagation in PL/SQL
    In PL/SQL (Procedural Language/Structured Query Language), efficient error management is crucial for ensuring smooth execution and robustness in database applications. One of the most important features in PL/SQL's exception handling mechanism is exception propagation. In this article, we will expla
    6 min read
  • Dart - Types of Exceptions
    Exception is a runtime unwanted event that disrupts the flow of code execution. It can be occurred because of a programmer’s mistake or by wrong user input. To handle such events at runtime is called Exception Handling. For example:- when we try to access the elements from the empty list. Dart Excep
    5 min read
  • Exception Handling in Programming
    Exception handling is a critical aspect of programming, enabling developers to manage unexpected or erroneous situations gracefully. In this article, we'll discuss the concept of exception handling, its importance, and best practices for implementing it effectively in various programming languages.
    7 min read
  • exception::what() in C++ with Examples
    The exception::what() used to get string identifying exception. This function returns a null terminated character sequence that may be used to identify the exception. Below is the syntax for the same: Header File: #include<exception> Syntax: virtual const char* what() const throw(); Return: Th
    2 min read
  • Exception handling in Objective-C
    Exception handling is an essential aspect of Objective-C programming, enabling developers to manage unforeseen errors effectively. Objective-C provides a robust set of tools and methodologies to handle exceptions, ensuring the stability and reliability of applications. Let's delve deeper into the nu
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences