开发者

ellipsis try catch on c++

开发者 https://www.devze.com 2023-04-12 09:13 出处:网络
Can an ellipsis try-catch be used to catch all the errors that can lead to a crash? Are there are 开发者_开发技巧any anomalies?

Can an ellipsis try-catch be used to catch all the errors that can lead to a crash? Are there are 开发者_开发技巧any anomalies?

try
{
//some operation
}
catch(...)
{
}


No, it'll only catch C++ exceptions, not things like a segfault, SIGINT etc.

You need to read up about and understand the difference between C++ exceptions and for want of a better word, "C-style" signals (such as SIGINT).


If the code inside try/catch block crashed somehow, the program is anyway in a non-recoverable state. You shouldn't try to prevent the crash, the best that the program can do is just let the process crash.

The "anomaly" is in the fact that your code only catches the exceptions, and not the errors. Even if the code is exception-safe (which may be not the case, if you are trying to work-around its mistakes by a try/catch block), any other inner error may bring the program into irrecoverable state. There is simply no way to protect the program from it.


Addition: look at this article at "The Old New Thing" for some insights.


It is the Catch All handler.
It catches all the C++ exceptions thrown from the try block. It does not catch segfault and other signals that cause your program to crash.

While using it, You need to place this handler at the end of all other specific catch handlers or it all your exceptions will end up being caught by this handler.

It is a bad idea to use catch all handler because it just masks your problems and hides the programs inability by catching all(even unrecognized) exceptions. If you face such a situation you better let the program crash, and create a crash dump you can analyze later and resolve the root of the problem.


It catches everything that is thrown, it is not limited to exceptions. It doesn't handle things like windows debug asserts, system signals, segfaults.

TEST(throw_int) {
    try {
        throw -1;
    } catch (std::exception &e) {
        std::cerr << "caught " << e.what() << std::endl;
    } catch (...) {
        std::cerr << "caught ..." << std::endl;
    }
}

Throwing an integer isn't really recommended though. It's better to throw something that inherits from std::exception.

You might expect to see something like this as a last ditch effort for documenting failure, though. Some applications aren't required to be very robust. Internal tools might cost more than they are worth if you went through the paces of making them better than hacked together crap.

int main(int argc, char ** argv) {
    try {
        // ...
    } catch (std::exception &e) {
        std::cerr << "error occured: " << e.what() << std::endl;
        return 1;
    }
    return 0;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消