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.
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
.
You simply cannot.
Catching with catch(...)
has two properties.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With