如何分辨.NET调用引发的异常? [英] How to tell whitch exceptions a .NET call throws?
问题描述
如果有以下代码:
data.SaveChanges();
(数据是 ObjectContext
)
MSDN文档列出了 OptimisticConcurrencyException 代码>.很好,但是我知道也可以抛出
UpdateException
(也可能抛出其他异常).我怎么知道方法可以抛出哪些异常?
The MSDN doc has listed the OptimisticConcurrencyException
as thrown. That's fine but I known that a UpdateException
can also be thrown (and possibly others too). How can I know which exceptions a method can throw?
我不想捕获 Exception
,因为我只想捕获我知道可以以某种方式处理的异常.一般来说,这不只是上面的示例.必须有某种方式知道内置" .NET方法会抛出哪个异常.
I do not want to catch Exception
as I only want to catch exceptions which I know I can handle in some way.
This is generally speaking - not just for the example above. There must be some way of knowing which exception a 'built-in' .NET method is throwing.
推荐答案
那不是本机"方法;这是由Microsoft(而不是您)编写的普通方法.
实际的本机方法无法引发托管异常(尽管COM互操作会将事物转换为托管异常)
That's not a "native" method; it's an ordinary method that happens to be written by Microsoft rather than you.
Actual native methods cannot throw managed exceptions (although COM interop will convert things to managed exceptions)
与Java不同,C#没有异常规范,因此没有固有的方式知道方法将抛出哪些异常.
Unlike Java, C# does not have exception specifications, so there is no inherent way of knowing what exceptions a method will throw.
您唯一的选择是文档或反编译器.
Your only options are the documentation or a decompiler.
这篇关于如何分辨.NET调用引发的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!