2011-05-01 112 views
1

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

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

有关我如何做到这一点的任何建议?

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

回答

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

和那些if条款,你可以投e到相应的异常类型来检索此异常的某些特定属性里面:((SomeCustomException)e).SomeCustomProperty

+0

是否有可能使用SWTICH /回事呢? – Homam 2011-05-01 10:19:29

+0

@杰克,不是一个可以接受的方式。见@亨克霍尔特曼[答案](http://stackoverflow.com/questions/5847741/exception-casting/5847799#5847799)。 – 2011-05-01 10:20:45

+0

谢谢,我不喜欢处理字符串。我认为你的解决方案更好。 – Homam 2011-05-01 10:22:34

3

如果所有的代码将在的if/else块那么最好使用多次捕获(记得把最具体的类型第一):

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 
    ... 
} 
2

我不能使用switch语句和异常对象。

如果你想使用一个开关,你总是可以使用类型名称:

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

这有可能的优点是,你不比赛亚型。

+0

字符串标识符非常难看。 – CodesInChaos 2011-05-01 10:19:24

+0

或typeof(ArgumentException).ToString()。我不确定,但这可能是好的。 – Homam 2011-05-01 10:23:14

+0

@Jack你需要一个常数来使用开关/外壳。没有开关/外壳,根本没有理由使用字符串。此代码的另一个问题是名称冲突。不同的异常类可能具有相同的名称。 – CodesInChaos 2011-05-01 10:27:27

0

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

// 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)); 
}