开发者

A couple of questions on exceptions/flow control and the application of custom exceptions

1) Custom exceptions can help make your intentions clear.

How can this be? The intention is to handle or log the exception, regardless of whether the type is built-in or custom.

The main reason I use custom exceptions is to not use one exception type to cover the same problem in different contexts (eg parameter is null in system code which may be effect by an external factor and an empty shopping basket). However, the partition between system and business-domain code and using different exception types seems very obvious and not making the most of custom exceptions. Related to this, if custom exceptions cover the business exceptions, I could also get all the places which are sources for exceptions at the business domain level using "Find all references". Is it worth adding exceptions if you check the arguments in a method for being null, use them a few times, and then add the catch? Is it a realistic risk that开发者_JAVA技巧 an external factor or some other freak cause could cause the argument to be null after being checked anyway?

2) What does it mean when exceptions should not be used to control the flow of programs and why not? I assume this is like:

if (exceptionVariable != null)
{

}

Is it generally good practise to fill every variable in an exception object? As a developer, do you expect every possible variable to be filled by another coder?


I'm not sure I understand your first point, but the second one means you shouldn't use exceptions to write code like this:

try {
   if ( something ) {
       stuff();
      if ( something else ) {
          throw 1;
      }
      more_stuff();
   }
}
catch( ... ) {
   yet_more_stuff();
}

where you are simply using the exception mechanism as a kind of goto. As for why not do this, well we have gotos, which are far more efficient and clearer in intent than exceptions are.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜