如何检查某些内容是.net异常还是自定义异常

时间:2013-12-03 15:11:30

标签: c# .net exception exception-handling

喜欢这个问题。我想检查异常集合上的某些内容是否是我的自定义异常,还是由.Net框架提供的Exception类。提前为您提供帮助。 \

请注意:

我不知道我的自定义异常的类名是什么,它可以被称为exceptionA,exceptionB或者例如xyzException

我有这样的代码:

    public IEnumerable<Type> GetClassHierarchy(Type type)   
    {
        if (type == null) yield break;

        Type typeInHierarchy = type;

        do
        {
            yield return typeInHierarchy;
            typeInHierarchy = typeInHierarchy.BaseType;
        }
        while (typeInHierarchy != null && !typeInHierarchy.IsInterface);
    }

    public string GetException(System.Exception ex)
    {
        if (ex == null)
        {
            return null;
        }

        if (ex.InnerException == null)
        {
            return ex.Message;
        }

        var exceptionHerarchy = GetClassHierarchy(ex.GetType());


        var isMyException = exceptionHerarchy.Any(t => t != typeof(System.Exception));

        if (isMyException)
        {
            return string.Format("{0};{1}", ex.Message, GetException(ex.InnerException));
        }
        else
        {
            return GetException(ex.InnerException);
        }

    }        

var isMyException = exceptionHerarchy.Any(t =&gt; t!= typeof(System.Exception));这是alays返回true,因为列表中可能有这种类型

5 个答案:

答案 0 :(得分:5)

很简单:

var t = myException.GetType().FullName;
bool isSystemException = (t.StartsWith("System."));

.NET Framework中的异常类型都在System或其子名称空间之一。

编辑:为了使这个更加漂亮,请为Exception类创建一个扩展函数:

public static bool IsSystemException(this Exception exception)
{
    return (exception.GetType().FullName.StartsWith("System."));
}

答案 1 :(得分:3)

双重重新考虑你为什么要这样做。然后使用以下解决方案之一。

<强>更好

从您提供的一个基类异常中派生所有自定义异常,并在try-catch块中捕获它。

<强>更糟

使用Reflection动态检查有关异常的一些信息,如其程序集:

ex.GetType().AssemblyQualifiedName

答案 2 :(得分:2)

使您的Exception类从自定义基类扩展。

        class MyBaseEception : Exception
        {
        }

        class MyCustomException : MyBaseException {}

        try
        {
        }
        catch (MyBaseException customException) {....}
        catch (Exception e)
        {
        }

虽然有人想知道你为什么要这样做。

答案 3 :(得分:0)

继承我的2便士......

try
        {

        }
        catch (Exception e)
        {
            if (e.GetType().Assembly.GetName().Name != "My.Own.Namespace")
            {
                // this is a .net exception?
            }
        }

答案 4 :(得分:0)

如果您不确定何时开火,为什么会有自定义例外? IME,当您想要处理特定案例时,通常会在业务逻辑周围使用自定义异常。否则依赖于框架。就代码而言,首先堆叠自定义异常,然后在不触发自定义异常的情况下捕获所有异常。

try
{
    //do something 
}
catch (MyCustomException ex)
{
    //log, continue, throw, etc
}
catch (Exception e)
{
    //log, continue, throw, etc
}