cpp: catch exception with ellipsis and see the information
Asked Answered
L

2

7

I know that you can catch "all exceptions" and print the exception by

try
{
    //some code...
}catch(const std::exception& e) {
   cout << e.what();
}

but this is just for exceptions derived from std::exception. I was wondering if there is a way to get some information from an ellipsis catch

try
{
    //some code...
}catch(...) {
   // ??
}

If the mechanism is the same as ellipsis for functions then I should be able to do something like casting the argument of the va_list and trying to call the what() method.

I haven't tried it yet but if someone knows the way I'd be excited to know how.

Lyrism answered 3/9, 2014 at 11:0 Comment(2)
Have you ever wondered how it could work to call what() on an int when s.o. throws one ?Brundisium
Obviously what I suggested wouldn't always work. I'm looking for a way to get something from it.Lyrism
J
6

Sorry, you can't do that. You can only access the exception object in a catch block for a specific exception type.

Jassy answered 3/9, 2014 at 11:7 Comment(0)
B
9

From C++11 and onwards, you can use std::current_exception &c:

std::exception_ptr p;
try {
    
} catch(...) {
    p = std::current_exception();
}

You can then "inspect" p by taking casts &c, albeit not in a portable way.

In earlier standards there is no portable way of intersecting the exception at a catch(...) site, other than re-throwing it with throw;.

Baltoslavic answered 25/7, 2017 at 11:23 Comment(4)
what is the &c you wrote?Lyrism
That's new to me (the &c) :) Can you show in your answer what can you do with this exception_ptr (what is the advantage)?Lyrism
You can't get any details out of std::exception_ptr, you can only rethrow it.Martensite
"&c" means "et cetera" ("and so on"). The Latin word "et" means "and". Replacing it with an ampersand saves a character and adds a somewhat old-fashioned flavor, but given that it confuses people here (where many people are not native English speakers), perhaps "and so on" would be better.Majewski
J
6

Sorry, you can't do that. You can only access the exception object in a catch block for a specific exception type.

Jassy answered 3/9, 2014 at 11:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.