[英]How do I find the exception type of an exception that gets thrown in C#?
I am using a library that doesn't seem to document the exceptions. 我使用的图书馆似乎没有记载例外情况。 This library is used to communicate with a product the company makes.
该库用于与公司生产的产品进行通信。 I want to be able to differentiate between the exceptions that get thrown but I don't know the names of the exceptions (for example between a communication timeout or under-voltage condition).
我希望能够区分抛出的异常,但是我不知道异常的名称(例如,在通信超时或欠压情况之间)。
All of their examples only use catch(Exception ex)
. 他们所有的示例仅使用
catch(Exception ex)
。 How can can I find what I need to use to catch the individual errors? 我怎样才能找到捕获单个错误所需的内容? When I do
ex.toString()
I get something like this: 当我执行
ex.toString()
,会得到如下信息:
System.Exception: Timeout
at CMLCOMLib.EcatObj.Initialize()
at copley_cmo_test.MainWindow.btnConnect_Click(Object sender, RoutedEventArgs e)
in c:\Users\adam.siembida\Desktop\copley_cmo_test\copley_cmo_test\MainWindow.xaml.cs:line 41
This: 这个:
System.Exception: Timeout
shows that they're just throwing a bare System.Exception
, eg 表明他们只是抛出一个空的
System.Exception
,例如
if (weHaveNoApiDesignSkills)
{
throw new Exception("Timeout");
}
It's possible that there are some exceptions which are better designed, but the one you've shown isn't promising :( 可能有一些例外情况设计得更好,但您所展示的例外情况并不乐观:(
Unfortunately unless you start using the message in the exception to differentiate between them (which is almost always a bad idea) you're stuck. 不幸的是,除非您开始在异常中使用消息来区分它们(这几乎总是一个坏主意),否则您将陷入困境。 It may be worth asking the authors of the library to see if they can improve matters for a future release.
也许值得图书馆的作者问一下,他们是否可以改善将来的发行版。
Catch it with a catch-all construct such as catch(Exception ex)
, then examine the Type
returned by ex.GetType()
. 用
ex.GetType()
例如catch(Exception ex)
捕获它,然后检查ex.GetType()
返回的Type
。 If it's equal to typeof(Exception)
, it means that they aren't throwing anything more specific than Exception
. 如果等于
typeof(Exception)
,则意味着它们没有抛出比Exception
更具体的东西。
顺便说一句,如果在捕获到异常时(即在catch块中)停止了您的操作,则在监视窗口中输入$exception
时,您将看到整个异常。
When the API in library which you are using is not documented properly , you should catch the base exception and log it not only by the message instead whole exception by converting the exception to string . 如果未正确记录正在使用的库中的API,则应捕获基本异常并不仅将消息记录下来,还应将异常转换为字符串,从而记录整个异常。 Eg.
例如。
try
{
//api call which throws exception.
}
catch(Exception ex)
{
//log ex.ToString();
}
use a decompiler for example: 使用反编译器,例如:
http://www.jetbrains.com/decompiler/ http://www.jetbrains.com/decompiler/
in .net there's no explicit exception declaration like in java so as i see it it's the only way. 在.net中,没有像Java中那样的显式异常声明,因此我认为这是唯一的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.