开发者

Exception casting

I am inserting different message based on the exception type.

I want to insert different custom message into the exception table based on the exception type. I cant use switch statements with e开发者_运维知识库xception object.

Any suggestion on how I can do this?

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

and inside those if clauses you can cast e to the corresponding exception type to retrieve some specific properties of this exception: ((SomeCustomException)e).SomeCustomProperty


If all the code will be in the if/else blocks then better to use multiple catch (remember to put the most specific types first):

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


I cant use switch statements with exception object.

If you want to use a switch, you could always use the Typename:

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

This has the possible advantage that you do not match subtypes.


You could unify the handling of different exception types (known at compile time) by a pre-defined dictionary. For example:

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

Usage:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜