【问题标题】:Can the orignial exception type be found in a rethrown generic exception?可以在重新抛出通用异常中找到原始异常类型吗?
【发布时间】:2011-08-05 08:17:24
【问题描述】:

我正在尝试捕获用户定义的权限异常 - 即用户做了一些他们的系统访问级别不允许的事情,引发了权限异常。我的问题是,异常被捕获,然后作为通用 System.Exception 重新抛出。

有什么方法可以推断出原始异常类型,而无需借助字符串比较,例如 if ex.ToString.Contains("Permission denied") Then ...

【问题讨论】:

    标签: vb.net .net-3.5 exception-handling


    【解决方案1】:

    您可以使用基异常类的 InnerException 属性,并循环直到 null

            try
            {
            }
            catch (Exception e)
            {
                while (e.InnerException != null)
                    e = e.InnerException;
    
                Console.WriteLine(e.Message);
            }
    

    【讨论】:

    • 如果至少有一个 InnerException,您的示例将抛出 NullReferenceException
    【解决方案2】:

    类似这样的:

    Try
    
    
    Catch e as Exception
        While e IsNot Nothing AndAlso Not TypeOf(e) is PermissionException
           e = e.InnerException;
        End While
    
        ' Rethrow if we can't handle it
        If e Is Nothing Then Throw 
    
        ' do whatever needs to be done when PermissionException is thrown
    
    End Try
    

    【讨论】:

    • 嗯...这看起来不错。我稍微修改了代码,使用 WHILE E ISNOTNOTHING,然后 if TypeOf(e) is PermissionException(将来有人可能还想处理其他异常),但代码不会在 TypeOf(e ) 是 PermissionException。它似乎无法确定类型。
    猜你喜欢
    • 2011-01-22
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 2012-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-27
    相关资源
    最近更新 更多