exception::bad_exception in C++ with Examples

Standard C++ contains several built-in exception classes, exception::bad_exception is one of them. This is an exception thrown by unexpected handler. Below is the syntax for the same:

Header File:

include<exception>

Syntax:

class bad_exception;

Return: The exception::bad_exception returns a null terminated character that is used to identify the exception.

Note: To make use of exception::bad_exception, one should set up the appropriate try and catch blocks.



Below are the examples to understand the implementation of exception::bad_exception in a better way:

Program 1 :

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ code for std::bad_exception
#include <bits/stdc++.h>
  
using namespace std;
  
void func()
{
    throw;
}
  
void geeksforgeeks() throw(bad_exception)
{
    throw runtime_error("test");
}
  
// main method
int main()
{
    set_unexpected(func);
  
    // try block
    try {
        geeksforgeeks();
    }
  
    // catch block to handle the errors
    catch (const bad_exception& gfg) {
        cout << "Caught exception "
             << gfg.what() << endl;
    }
    return 0;
}

chevron_right


Output:

Caught exception std::bad_exception

Program 2 :

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ code for std::bad_exception
#include <bits/stdc++.h>
  
using namespace std;
  
void gfg()
{
    throw;
}
  
void A_Computer_Science_Portal_For_Geeks()
     throw(bad_exception)
{
    throw runtime_error("test");
}
  
// main method
int main()
{
    set_unexpected(gfg);
  
    // try block
    try {
        A_Computer_Science_Portal_For_Geeks();
    }
  
    // catch block to handle the errors
    catch (const bad_exception& a) {
        cout << "Caught exception "
             << a.what() << endl;
    }
    return 0;
}

chevron_right


Output:

Caught exception std::bad_exception

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

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.




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.