如何获得在C#中的异常错误code [英] How to get Exception Error Code in C#

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

问题描述

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

当我调用上面的WMI方法,我希望得到Access denied。在我的catch块我想确保提出的例外是确实拒绝访问。有没有一种方法,我可以得到的错误code呢? Win32错误code的访问请求被拒绝为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.

感谢

推荐答案

试试这个检查异常,内层的<一个href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.win32exception.aspx\">Win32Exception派生的异常。

try this to check the exception and the inner one for a Win32Exception derived exception.

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   
}

由于在评论中,你真的需要看到实际被抛出什么异常,了解你可以做什么,在这种情况下,具体的缺点是pferred经过短短捕捉异常$ P $。是这样的:

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){  
     int code = ex.HResult;
 }

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

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