Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cpp: catch exception with ellipsis and see the information

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.

like image 942
ZivS Avatar asked Sep 03 '14 11:09

ZivS


People also ask

How do you catch thrown exceptions in C++?

Exception handling in C++ is done using three keywords: try , catch and throw . To catch exceptions, a portion of code is placed under exception inspection. This is done by enclosing this portion of code in a try block. When an exception occurs within the try block, control is transferred to the exception handler.

What is std :: exception in C++?

std::exception class exception; Provides consistent interface to handle errors through the throw expression.

What happens after exception is caught C++?

After an exception has been handled, the program execution resumes after the try-catch block, not after the throw. The catch block can be, and usually is, located in a different function/method than the point of throwing. In this way, C++ supports non-local error handling.

Does catching an exception stop execution C++?

catch is designed to leave the program running after an exception was succesfully caught. You may just call abort() or exit() directly in the catch block.


1 Answers

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.

In earlier standards there is no portable way of inspecting the exception at a catch(...) site.

like image 116
Bathsheba Avatar answered Sep 30 '22 11:09

Bathsheba