Skip to content
Related Articles

Related Articles

exception::what() in C++ with Examples
  • Last Updated : 28 May, 2020

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: The function std::what() return a null terminated character sequence that is used to identify the exception.

Note: To make use of std::what(), one should set up the appropriate try and catch blocks.



Below are the programs to understand the implementation of std::what() in a better way:

Program 1:




// C++ code for exception::what()
#include <bits/stdc++.h>
  
using namespace std;
  
struct gfg : exception {
    const char* what() const noexcept
    {
        return "GeeksforGeeks!! "
               "A Computer Science"
               " Portal For Geeks";
    }
};
  
// main method
int main()
{
  
    // try block
    try {
        throw gfg();
    }
  
    // catch block to handle the errors
    catch (exception& gfg1) {
        cout << gfg1.what();
    }
  
    return 0;
}
Output:
GeeksforGeeks!! A Computer Science Portal For Geeks

Program 2:




// C++ code for exception::what()
  
#include <bits/stdc++.h>
  
using namespace std;
  
struct geeksforgeeks : exception {
    const char* what() const noexcept
    {
        return "Hey!!";
    }
};
  
// main method
int main()
{
  
    // try block
    try {
        throw geeksforgeeks();
    }
  
    // catch block to handle the errors
    catch (exception& gfg) {
        cout << gfg.what();
    }
  
    return 0;
}
Output:
Hey!!

Reference: http://www.cplusplus.com/reference/exception/exception/what/

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.
My Personal Notes arrow_drop_up
Recommended Articles
Page :