Open In App

exception::bad_exception in C++ with Examples

Last Updated : 28 May, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report
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 : CPP14
// 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;
}
Output:
Caught exception std::bad_exception
Program 2 : CPP14
// 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;
}
Output:
Caught exception std::bad_exception
Reference: http://www.cplusplus.com/reference/exception/bad_exception/

Next Article
Article Tags :
Practice Tags :

Similar Reads