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

Raf*_*ski 2 .net c# exception-handling exception

就像问题一样.我想检查异常集合上的某些内容是否是我的自定义异常,还是由.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);
        }

    }        
Run Code Online (Sandbox Code Playgroud)

var isMyException = exceptionHerarchy.Any(t => t!= typeof(System.Exception)); 这是alays返回true,因为列表中可能存在此类型

Roy*_*tus 7

非常简单:

var t = myException.GetType().FullName;
bool isSystemException = (t.StartsWith("System."));
Run Code Online (Sandbox Code Playgroud)

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

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

public static bool IsSystemException(this Exception exception)
{
    return (exception.GetType().FullName.StartsWith("System."));
}
Run Code Online (Sandbox Code Playgroud)

  • 假设没有人在系统命名空间中创建自定义异常......这种假设可能不成立. (4认同)
  • @RoyDictus但是你可以编写一些程序,无论是否使用*依赖于智能用户的脆弱程序都可以使用.认为世界上每个人都不愚蠢会导致失望. (3认同)