如何使用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;
.