本文介绍了捕获主(...)中的异常是否有意义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在项目中发现了一些代码:

I found some code in a project which looks like that :

int main(int argc, char *argv[])
{
  // some stuff

 try {
  theApp.Run();
 } catch (std::exception& exc) {
  cerr << exc.what() << std::endl;
  exit(EXIT_FAILURE);
 }
 return (EXIT_SUCCESS);
}

我不明白为什么异常被捕获。如果没有,应用程序将简单地退出并且将打印例外。

I don't understand why the exceptions are being catched. If they weren't, the application would simply exit and the exception would be printed.

你看到有什么好的理由来捕捉异常吗?

Do you see any good reason to catch exceptions here ?

编辑:我同意打印异常错误是很好的。但是,再推翻这个例外是不是更好?我有一种感觉,我们在这里吞下它...

EDIT : I agree that it is good to print the exception error. However, wouldn't it be better to rethrow the exception ? I have the feeling that we are swallowing it here...

推荐答案

如果一个异常未被捕获,那么标准没有定义堆叠是否展开。所以在一些平台上,析构函数将被调用,而其他的程序将立即终止。在顶层捕获确保析构函数总是被调用。

If an exception is uncaught, then the standard does not define whether the stack is unwound. So on some platforms destructors will be called, and on others the program will terminate immediately. Catching at the top level ensures that destructors are always called.

所以,如果你没有在调试器下运行,可能明智的做法是:(... )以及std :: exception。那么您的应用程序代码可以用RAII清理,即使是致命的异常。在许多这种情况下,您实际上不需要清理,因为操作系统将为您做。但是,例如,您可能希望尽可能远离远程服务断开连接,并且可能存在过程外部的资源,例如命名管道/互斥体,您希望销毁而不是泄漏。

So, if you aren't running under the debugger, it's probably wise to catch everything: (...) as well as std::exception. Then your application code can clean up with RAII even on a fatal exception. In many such cases you don't actually need to clean up, since the OS will do it for you. But for instance you might prefer to disconnect cleanly from remote services where possible, and there might be resources external to the process, such as named pipes/mutexes, that you'd prefer to destroy rather than leaking.

对我来说,重新发现异常似乎是有限的使用,因为你已经失去了最初被抛出的上下文。我认为在调试器中捕获一个未捕获的异常比将错误记录到std :: cerr更为嘈杂,所以如果有机会丢失日志记录,重新启动将是一个明智的举动。

Rethrowing the exception in main seems to me of limited use, since you've already lost the context in which it was originally thrown. I suppose that trapping an uncaught exception in the debugger is noisier than just logging the fault to std::cerr, so rethrowing would be the smart move if there's a chance of missing the logging.

如果您希望调试器在调试模式下捕获意外的情况,在释放模式下抛出异常,最终导致退出,那么还有其他方法可以使异常处于未被捕获的状态,以便调试器看到它。例如,您可以使用断言宏。当然,这不利于意外和不可预测的条件,如硬件异常如果您在.NET上使用SEH。

If you want the debugger to trap unexpected conditions in debug mode, which in release mode throw an exception that eventually results in an exit, then there are other ways to do that than leaving the exception uncaught so that the debugger sees it. For example, you could use assert macros. Of course, that doesn't help with unexpected and unpredictable conditions, like hardware exceptions if you're using SEH on .NET.

这篇关于捕获主(...)中的异常是否有意义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 13:50