开发者

Can the orignial exception type be found in a rethrown generic exception?

I'm trying to catch a user defined permission exception - i.e. a user does something their level of system access won't allow, permission exception is thrown. My problem is, the exception i开发者_JS百科s caught and then rethrown as a genertic System.Exception.

Is there any way I can deduce the original exception type, without resorting to string comparisons, like if ex.ToString.Contains("Permission denied") Then ...?


You could use the InnerException property of the base Exception class, and loop until null

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

            Console.WriteLine(e.Message);
        }


Something like this:

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜