如何在 C# 中获取异常错误代码 [英] How to get Exception Error Code in C#

查看:96
本文介绍了如何在 C# 中获取异常错误代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

try
{
     object result = processClass.InvokeMethod("Create", methodArgs);
}
catch (Exception e)
{  
    // Here I was hoping to get an error code.
}

当我调用上述 WMI 方法时,我预计会被拒绝访问.在我的 catch 块中,我想确保引发的异常确实是针对拒绝访问的.有什么办法可以得到它的错误代码吗?Access Denied 的 Win32 错误代码是 5.我不想在错误消息中搜索被拒绝的字符串或类似的东西.

When I invoke the above WMI method I am expected to get Access Denied. In my catch block I want to make sure that the exception raised was indeed for Access Denied. Is there a way I can get the error code for it ? Win32 error code for Acceess Denied is 5. I dont want to search the error message for denied string or anything like that.

谢谢

推荐答案

您可以使用它来检查 Win32Exception 派生异常.

catch (Exception e) {  
    var w32ex = e as Win32Exception;
    if(w32ex == null) {
        w32ex = e.InnerException as Win32Exception;
    }    
    if(w32ex != null) {
        int code =  w32ex.ErrorCode;
        // do stuff
    }    
    // do other stuff   
}

从 C# 6 开始,when可以在 catch 语句中使用,以指定处理程序必须为真才能执行特定异常的条件.

Starting with C# 6, when can be used in a catch statement to specify a condition that must be true for the handler for a specific exception to execute.

catch (Win32Exception ex) when (ex.InnerException is Win32Exception) {
    var w32ex = (Win32Exception)ex.InnerException;
    var code =  w32ex.ErrorCode;
}

在评论中,您确实需要查看实际抛出的异常以了解您可以做什么,并且在这种情况下,特定捕获优于仅捕获异常.类似的东西:

As in the comments, you really need to see what exception is actually being thrown to understand what you can do, and in which case a specific catch is preferred over just catching Exception. Something like:

  catch (BlahBlahException ex) {  
      // do stuff   
  }

还有 System.Exception 有一个 HRESULT

 catch (Exception ex) {  
     var code = ex.HResult;
 }

但是,它仅适用于 .NET 4.5 以上.

However, it's only available from .NET 4.5 upwards.

这篇关于如何在 C# 中获取异常错误代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆