且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-07 20:55:10

您可以使用它来检查 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.