铸造异常

本文关键字:异常 | 更新日期: 2023-09-27 17:53:56

我将根据异常类型插入不同的消息。

我想根据异常类型在异常表中插入不同的自定义消息。我不能将switch语句与异常对象一起使用。

关于我该怎么做,有什么建议吗?

private void ExceptionEngine(Exception e)
{
    if (e.)
    {
        exceptionTable.Rows.Add(null, e.GetType().ToString(), e.Message);
    }

铸造异常

if (e is NullReferenceException)
{
    ...
}
else if (e is ArgumentNullException)
{
    ...
}
else if (e is SomeCustomException)
{
    ...
}
else
{
   ...
}

在这些if子句中,您可以将e强制转换为相应的异常类型,以检索该异常的一些特定属性:((SomeCustomException)e).SomeCustomProperty

如果所有代码都在If/else块中,那么最好使用多个catch(记住先放最特定的类型(:

try {
  ...
} catch (ArgumentNullException e) {
  ...
} catch (ArgumentException e) { // More specific, this is base type for ArgumentNullException
  ...
} catch (MyBusinessProcessException e) {
  ...
} catch (Exception e) { // This needs to be last
  ...
}

我不能将switch语句与异常对象一起使用。

如果你想使用交换机,你可以总是使用Typename:

switch (e.GetType().Name)
{
   case "ArgumentException" : ... ;
}

这可能有一个优点,即您可以匹配子类型。

您可以通过预定义的字典统一处理不同的异常类型(在编译时已知(。例如:

//  Maps to just String, but you could create and return whatever types you require...
public static class ExceptionProcessor {
    static Dictionary<System.Type, Func<String, Exception> sExDictionary = 
     new Dictionary<System.Type, Func<String, Exception> {
        { 
            typeof(System.Exception), _ => {
                return _.GetType().ToString();
            }
        },
        { 
            typeof(CustomException), _ => { 
                CustomException tTmp = (CustomException)_; 
                return tTmp.GetType().ToString() + tTmp.CustomMessage; 
            }
        }
    }
    public System.String GetInfo(System.Exception pEx) {
        return sExDictionary[pEx.GetType()](pEx);
    }
}

用法:

private void ExceptionEngine(Exception e) {
    exceptionTable.AddRow(ExceptionProcessor.GetInfo(e));
}