我正在根据异常类型插入不同的消息。
我想根据异常类型在异常表中插入不同的自定义消息。我不能对异常对象使用switch语句。
我该怎么做有什么建议吗?
private void ExceptionEngine(Exception e)
{
if (e.)
{
exceptionTable.Rows.Add(null, e.GetType().ToString(), e.Message);
}发布于 2011-05-01 18:06:40
if (e is NullReferenceException)
{
...
}
else if (e is ArgumentNullException)
{
...
}
else if (e is SomeCustomException)
{
...
}
else
{
...
}在这些if子句中,您可以将e转换为相应的异常类型,以检索此异常的一些特定属性:((SomeCustomException)e).SomeCustomProperty
发布于 2011-05-01 18:13:22
如果所有代码都在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
...
}发布于 2011-05-01 18:15:18
我不能将switch语句与exception对象一起使用。
如果要使用开关,可以始终使用Typename:
switch (e.GetType().Name)
{
case "ArgumentException" : ... ;
}这可能有一个好处,那就是您不匹配子类型。
https://stackoverflow.com/questions/5847741
复制相似问题