.net 异常捕获块
以下 catch 块有什么区别?
try
{
...
}
catch
{
...
}
我
try
{
...
}
catch(Exception)
{
...
}
意识到,在任何一种情况下,异常实例都不可用,但是我可以用一个实例做一些其他实例做不到的事情吗?
What's the difference between the following catch blocks?
try
{
...
}
catch
{
...
}
and
try
{
...
}
catch(Exception)
{
...
}
I realize, in either case, the exception instance is not available but is there anything that I can do with one that is not possible with the other?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
它们几乎相同。
来自 C# 语言规范,第 8.10 节:
请注意,虽然 C# 区分了两者,但它们实际上与 .NET 2.0 相同,如 此博客:
They are almost the same.
From the C# Language Specification, section 8.10:
Note that while C# differentiates between the two, they are effectively the same as of .NET 2.0, as noted by this blog:
不带参数的
catch
将捕获不符合 CLS 的异常,这与catch (Exception)
不同。catch
without arguments will catch non CLS-compliant exceptions, unlikecatch (Exception)
.来自为什么catch(Exception)/empty捕获不好
From Why catch(Exception)/empty catch is bad
如果你看一下生成的 IL,这里有区别:
并且只是简单的捕获:
所以从理论上讲,如果你创建一种可以具有不从 System.Exception 继承的异常的语言,那么就会有区别......
If you look at the generated IL here's the difference:
and just plain catch:
So in theory, if you create a language that can have exceptions NOT inherit from System.Exception, there would be a difference...
非 CLS 遵守语言(如 C++/CLI)可以抛出不是从 System.Exception 类派生的对象。第一个代码示例将允许您执行 catch 块中的代码,但您无法检查抛出的对象本身。这几乎从来都不是问题,但也可能是问题。
Non-CLS adhering languages (like C++/CLI) can throw objects not derived from System.Exception class. The first code sample will allow you to execute code in the catch block, though you can't examine the thrown object itself. This is almost never an issue, but it could be.
我不相信有什么区别,像 Resharper 这样的工具会告诉您在第二个实例中
catch(Exception)
是多余的,除非您还插入了其他catch(SomeSubclassException)
异常处理块位于Exception
之前,以便对其他异常情况应用不同的异常处理逻辑。I don't believe there is a difference, and a tool like Resharper would tell you that the
catch(Exception)
is redundant in the second instance, UNLESS you also inserted othercatch(SomeSubclassException)
exception handling blocks beforeException
to apply different exception handling logic for other exception conditions.