如何使用try和catch捕获c#中的所有异常? [英] How to catch all exceptions in c# using try and catch?

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

问题描述

我想写一些尝试捕获任何类型或异常的代码,这样的代码够用吗(在Java中就是这样)?

I want to write some try and catch that catch any type or exception, is this code is enough (that's the way to do in Java)?

try {
code....
}
catch (Exception ex){}

或者应该是

try {
code....
}
catch {}

?

推荐答案

这两种方法都将捕获所有异常.您的两个代码示例之间没有显着差异,只是第一个示例将生成编译器警告,因为已声明但未使用 ex .

Both approaches will catch all exceptions. There is no significant difference between your two code examples except that the first will generate a compiler warning because ex is declared but not used.

但是请注意,某些例外是特殊的,会自动重新抛出.

But note that some exceptions are special and will be rethrown automatically.

ThreadAbortException 是可以捕获的特殊异常,但是它将在catch块的末尾自动再次引发.

ThreadAbortException is a special exception that can be caught, but it will automatically be raised again at the end of the catch block.

http://msdn.microsoft.com/en-us/library/system.threading.threadabortexception.aspx

如评论中所述,捕获并忽略所有异常通常是一个非常不好的主意.通常,您想执行以下操作之一:

As mentioned in the comments, it is usually a very bad idea to catch and ignore all exceptions. Usually you want to do one of the following instead:

  • 捕获并忽略您知道不会致命的特定异常.

  • Catch and ignore a specific exception that you know is not fatal.

catch (SomeSpecificException)
{
    // Ignore this exception.
}

  • 捕获并记录所有异常.

  • Catch and log all exceptions.

    catch (Exception e)
    {
        // Something unexpected went wrong.
        Log(e);
        // Maybe it is also necessary to terminate / restart the application.
    }
    

  • 捕获所有异常,进行一些清理,然后重新抛出异常.

  • Catch all exceptions, do some cleanup, then rethrow the exception.

    catch
    {
        SomeCleanUp();
        throw;
    }
    

  • 请注意,在最后一种情况下,使用 throw; 而不是 throw ex; 抛出异常.

    Note that in the last case the exception is rethrown using throw; and not throw ex;.

    这篇关于如何使用try和catch捕获c#中的所有异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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