找出方法在 C# 中可能抛出的异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/264747/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Finding out what exceptions a method might throw in C#
提问by Helephant
Is there any way to find out what exceptions might be thrown by any method in .NET code? Ideally I want to see what might be thrown and choose which ones I want to handle. I guess I want the information you'd get from the throws clause in java.
有什么方法可以找出 .NET 代码中的任何方法可能抛出哪些异常?理想情况下,我想看看可能会抛出什么并选择我想要处理的那些。我想我想要你从 java 中的 throws 子句中得到的信息。
The situation is I'm doing a linq query on an xml document from the network and want to know what could go wrong. I could open up the assembly in reflector and have a look but I thought there might be an easier way.
情况是我正在对来自网络的 xml 文档进行 linq 查询,想知道可能会出现什么问题。我可以在反射器中打开组件并查看一下,但我认为可能有更简单的方法。
采纳答案by Marc Gravell
.NET does not have enforced ("checked") exceptions like java. The intellisense mightshow this information, if the developer has added a /// <exception.../>
block - but ultimately more exceptions can happen than you expect (OutOfMemoryException
, ThreadAbortException
, TypeLoadException
, etc can all happen fairly unpredictably).
.NET 没有像 java 这样的强制(“检查”)异常。如果开发人员添加了一个块,intellisense可能会显示此信息/// <exception.../>
- 但最终可能会发生比您预期更多的异常(OutOfMemoryException
、ThreadAbortException
、TypeLoadException
等都可能相当不可预测地发生)。
In general, you should have an idea of what things are likely to go wrong, and which ones you can actually do something useful about. In most cases, the correct behaviour is to let the exception bubble up (just running any "finally" code to release resources).
一般来说,您应该了解哪些事情可能会出错,哪些事情您实际上可以做一些有用的事情。在大多数情况下,正确的行为是让异常冒泡(只需运行任何“finally”代码来释放资源)。
Eric Lippert has a good blog on this subject here.
Eric Lippert 在这里有一篇关于这个主题的好博客。
回答by OregonGhost
As long as you're using BCL classes, they are all completely documented and Intellisense therefore displays any exception a method can throw. Other than that (and reading the docs), there is no way, I think.
只要您使用 BCL 类,它们都会被完整记录下来,因此 Intellisense 会显示方法可能抛出的任何异常。除此之外(和阅读文档),我认为没有办法。
回答by reshefm
I think that Exception huntercan provide this information however it costs money...
我认为异常猎人可以提供这些信息,但它需要花钱......
回答by Steve Sheldon
After reading another article about this on StackOverflow, I built on top of that other answer to write a tool to do this, you can get the source code from GitHub here:
在 StackOverflow 上阅读了另一篇关于此的文章后,我在其他答案的基础上编写了一个工具来执行此操作,您可以从 GitHub 此处获取源代码:
you can also read more here:
你也可以在这里阅读更多: