Open In App

typeinfo::bad_typeid in C++ with Examples

Last Updated : 28 May, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

Standard C++ contains several built-in exception classes, typeinfo::bad_typeid is one of them. This is an exception thrown on typeid of null pointer. Below is the syntax for the same:

Header File:

<typeinfo>

Syntax:

class bad_typeid;

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

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

Below are the examples to understand the implementation of typeinfo::bad_typeid in a better way:

Program 1:




// C++ code for std::bad_typeid
#include <bits/stdc++.h>
  
using namespace std;
  
struct gfg {
    virtual void func();
};
  
// main method
int main()
{
    gfg* g = nullptr;
  
    // try block
    try {
        cout << typeid(*g).name()
             << endl;
    }
  
    // catch block to handle the errors
    catch (const bad_typeid& fg) {
        cout << fg.what() << endl;
    }
  
    return 0;
}


Output:

std::bad_typeid

Program 2:




// C++ code for std::bad_typeid
#include <bits/stdc++.h>
  
using namespace std;
  
struct geeksforgeeks {
    virtual void
    A_Computer_Science_Portal_For_Geeks();
};
  
// main method
int main()
{
    geeksforgeeks* gfg = nullptr;
  
    // try block
    try {
        cout << typeid(*gfg).name() << endl;
    }
  
    // catch block to handle the errors
    catch (const bad_typeid& fg) {
        cout << fg.what() << endl;
    }
  
    return 0;
}


Output:

std::bad_typeid

Reference: http://www.cplusplus.com/reference/typeinfo/bad_typeid/



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads