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: 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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Output:

GeeksforGeeks!! A Computer Science Portal For Geeks

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Output:

Hey!!

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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.