如何在一个catch块中捕获所有类型的异常? [英] How can I catch all types of exceptions in one catch block?

查看:1558
本文介绍了如何在一个catch块中捕获所有类型的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中,我试图捕获一个catch中的所有类型的异常(如C#中的 catch(Exception))。怎么做而且还有什么可以得到除以零的例外?

解决方案

  catch (...)
{
//处理未覆盖的异常。
}

重要注意事项:




  • 一个更好的方法是捕获特定类型的异常,您可以从中实际恢复,而不是所有可能的异常。

  • catch(...)将也可以捕获某些严重的系统级异常(根据编译器的不同),您将无法从中可靠地恢复。以这种方式抓住他们,然后吞咽并继续,可能会导致您的程序中出现更严重的问题。

  • 根据您的上下文,使用catch(...)可以接受,异常被重新抛出。在这种情况下,您记录所有有用的本地状态信息,然后重新抛出异常以允许它向上传播。但是,如果您选择此路线,您应该阅读 RAII模式


In C++, I'm trying to catch all types of exceptions in one catch (like catch(Exception) in C#). How is it done? And what's more, how can one catch divide-by-zero exceptions?

解决方案

catch (...)
{
   // Handle exceptions not covered.
}

Important considerations:

  • A better approach is to catch specific types of exception that you can actually recover from as opposed to all possible exceptions.
  • catch(...) will also catch certain serious system level exceptions (varies depending on compiler) that you are not going to be able to recover reliably from. Catching them in this way and then swallowing them and continuing could cause further serious problems in your program.
  • Depending on your context it can be acceptable to use catch(...), providing the exception is re-thrown. In this case, you log all useful local state information and then re-throw the exception to allow it to propagate up. However you should read up on the RAII pattern if you choose this route.

这篇关于如何在一个catch块中捕获所有类型的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆