开发者

Exception Handling and program logic

We all know that using Exception Handling to control your program's logical flow is bad. That is, you would never do:

开发者_开发百科public void someMethod(Object someObject) {
    try {
        someObject.doSomething();
    } catch (NullPointerException npe) {
        //handle Null case
    } 
}

over

public void someMethod(Object someObject) {
    if(someObject != null) {
        someObject.doSomething();
    }
}

My question is, what are some good exceptions (har!) to this rule? In Java, I can think of using MalformedURLException to determine if a String is a URL or not. What other cool abuses of exception handling have you seen?


When you throw them over a service boundary - from the server to the client (like fault exception in WCF - there is a good way to pass unexpected errors from the server back to the client, or SqlExpcetion from the sql server..)

Sometimes it's ok to use them, to save programming time (like format exception when you convert string to something else) ect....


The .NET Framework 1.0 and 1.1 didn't have a lot of the TryParse methods it has now. In the old days, I did stuff like this a lot:

bool IsInteger(string str)
{
  try
  {
    Int32.Parse(str);
    return true;
  } 
  catch (FormatException)
  {
    return false;
  }
}


I've used this quite a bit while working with java reflect.

For example, in the case where a field is present in some class higher up(I mean one of the super classes) and not the class itself, I had written something like this -

try{
//some stuff like follows
Field f = cls.getDeclaredField(fieldName);
}
catch(NoSuchFieldException e){
cls = cls.getSuperClass();
}

Of course, this is under a loop and the loop exit criteria is when cls is null..

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜