简体   繁体   English

如何在C#中获取异常代码?

[英]How can I get exception code in C#?

Is there anything like exception code? 有什么像异常代码吗? that i can know that on different languages operation system i can recognize the same exception? 我可以知道在不同的语言操作系统我可以识别相同的异常?

I need to recognize 'Acces to the COMn Port is denied' and then do some action, is that possible? 我需要认识到'COMn端口的访问被拒绝',然后做一些动作,这可能吗? has this exception any specified type? 有任何指定类型的此异常?

From the sounds of it you will be getting a System.UnauthorizedAccessException (this assumption has been made from Googling the error message and finding this forum). 从它的声音你将得到一个System.UnauthorizedAccessException (这个假设是通过谷歌搜索错误消息并找到这个论坛)。 To handle this, you would need to use catch clauses in a try-catch statement that are specific to this exception type. 要处理此问题,您需要在try-catch语句中使用特定于此异常类型的catch子句。 So, in C# you would do something like: 所以,在C#中你会做类似的事情:

try
{
    // ... Run some code that might cause the error in question ...
}
catch (System.UnauthorizedAccessException ex)
{
    // ... Run some code that handles the error in question ...
}

There is no concept of a global exception code in .NET -- and there really could never be, since it implies that every author of every exception class on the planet would have to collaborate in order to choose codes. .NET中没有全局异常代码的概念 - 而且实际上永远不可能,因为它意味着地球上每个异常类的每个作者都必须合作才能选择代码。

You also cannot assume that a particular message signals an exception of a particular type, since the message can (in the general case) be freely chosen at the throw site. 您也不能假设特定消息表示特定类型的异常,因为消息可以(在一般情况下)在投掷站点自由选择。

You could do a type switch on exception.GetType() to find what the runtime type of an exception is, but that is not guaranteed to be a solution (it depends on what was actually thrown, which could be a vanilla System.Exception for all we know). 可以exception.GetType()上做一个类型切换来查找exception.GetType()的运行时类型,但是这不能保证是一个解决方案(它取决于实际抛出的内容,这可能是一个vanilla System.Exception for我们都知道)。

What exactly are you trying to achieve? 你到底想要达到什么目的?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM