Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print exception message in C++ with catch(...) {..}

Tags:

c++

exception

This is the sample code

int main()
{
    string S;
    getline(cin, S);
    try {
        int val = stoi(S);
    } catch(...) {
       // cout << //exception message ; I want to print the exception message. 
    }
    return 0;
}

Is it possible to print an exception message in this case ?. The message will show what kind of exception was thrown. I am trying this because , stoi() can throw multiple exceptions and I want to catch all of them and print the type of exception that was thrown, instead of using a separate catch block for each exception type.

like image 667
code_lantern Avatar asked Oct 19 '25 09:10

code_lantern


2 Answers

All C++ library exceptions inherit from std::exception.

So the simplest thing to do is to catch a reference to it:

catch (const std::exception &e)
{
    std::cout << "Caught " << e.what(); << std::endl;
}

This will catch all exceptions thrown by stoi.

like image 144
Sam Varshavchik Avatar answered Oct 22 '25 01:10

Sam Varshavchik


You simply cannot.

Catching with catch(...) has two properties.

  1. It can capture anything thrown.
  2. You don't have access to whatever has been caught.

Which means you cannot use .what() on the object caught, because you have no access to it.

If you have a warrant that std::exception will be thrown, then you could simply capture std::exception const&

catch(std::exception const& e){
    std::cout<<"Exception: "<<e.what()<<std::endl;
}
like image 23
Karen Baghdasaryan Avatar answered Oct 21 '25 23:10

Karen Baghdasaryan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!