捕获一般异常时,如何确定原始异常类型? [英] When catching a general exception, how can I determine the original exception type?

查看:337
本文介绍了捕获一般异常时,如何确定原始异常类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在.NET中捕获异常时,可以根据需要具有任意多个特定于类型的异常块。但是我通常尝试至少有一个一般异常捕获块。但是,是否有一种方法可以获取泛型异常处理程序捕获的真实异常的类型,也许使用反射?

When catching an exception in .NET, you can have as many type-specific exception blocks as needed. But I usually try to have at least one "general" exception catch block. But is there a way to get the type of the "real" exception thrown that is caught by the generic exception handler, perhaps using reflection?

例如,如果我有

Catch ex As System.ServiceModel.FaultException(Of InvalidUser)
     ProcessModuleLoadException(Me, ex)
Catch ex As System.ServiceModel.FaultException(Of SQLExceptions)
     ProcessModuleLoadException(Me, ex)
Catch ex As System.ServiceModel.FaultException(Of DataNullReference)
     ProcessModuleLoadException(Me, ex)
Catch ex As System.ServiceModel.FaultException
     ProcessModuleLoadException(Me, ex)
Catch ex As Exception
     ProcessModuleLoadException(Me, ex)

(即使在每种例外情况下我都做同样的事情,我还是将它们拆分出来进行调试)。

(I have broken them out for debugging, even though I do the same thing with each exception).

简而言之,在将Ex捕获为System.ServiceModel.FaultException中,我想检查 ex并获取异常的基本真实类型,即eit

In short, in "Catch ex As System.ServiceModel.FaultException" I want to examine "ex" and get the base "real" type of the exception, either as a type (mostly for debugging so I can add another catch block) or as a string (for logging).

但是,在Catch块中, ex是一种类型(主要用于调试,因此我可以添加另一个catch块)或用作字符串(用于记录日志)。已被强制转换为其父类,因此似乎丢失了任何原始属性和有关原始异常的信息。

But, inside the Catch block, "ex" has already been cast to it's parent class, so any original properties and information about the original exception seem to be lost.

建议?

推荐答案

即使 Exception 已强制转换为其父类,您仍然可以调用 GetType 以获得其基本的具体类型(请原谅我的C#):

Even though the Exception has been cast to its parent class, you can still call GetType to obtain its underlying concrete type (pardon my C#):

try {
    // Do stuff
}
catch(Exception ex) {
    Type exceptionType = ex.GetType();
}

如果这只是出于诊断目的,则可以记录 ex.ToString(),默认情况下包括基础类型(除了堆栈跟踪等):

If this is just for diagnostic purposes, you can log ex.ToString(), which includes the underlying type by default (in addition to the stack trace, etc.) like this:

System.ArgumentException: lastName
   at Tests.Program.Main(String[] args) in ...\Program.cs:line 22

这篇关于捕获一般异常时,如何确定原始异常类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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