File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Art of Java: Ch 13 Control Flow vs. Exception handling

 
Junilu Lacar
Bartender
Pie
Posts: 6547
21
Java Linux Mac Scala Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Section 13.3.4 recommends that the controller handle exceptions. In Struts 1.1 you can use declarative exception handling which is nice. I have also seen code where try-catch blocks in the execute method create appropriate ActionErrors and set the ActionForward to be returned.
The recent onjava.com article by Gunjan Doshi recommends that we should never use exceptions for flow control. I have a hard time reconciling these two pieces of advice and explaining to my teammates why having other layers (e.g. the application/business delegate/boundary objects) throw exceptions and letting the Controller catch them and decide what to do next accordingly is not the same as using exceptions for flow control. Perhaps it is using exceptions to control flow but how would you explain why this is acceptable (and recommended) practice for this case and not for others? Can you give more examples where using exceptions for flow control is or is not acceptable?
 
Neal Ford
Author
Ranch Hand
Posts: 82
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Junilu -
In Struts 1.1 you can use declarative exception handling which is nice.

I quite agree -- my struts chapter takes advantage of this facility.
Perhaps it is using exceptions to control flow but how would you explain why this is acceptable (and recommended) practice for this case and not for others? Can you give more examples where using exceptions for flow control is or is not acceptable?

The distinction here is between workflow and flow control. Workflow defines how the user works with the application. In that case, it is appropriate for the controller (or controller proxy, Action) to catch the exception and foward to an error page or other resource.
Flow control is another matter. Here is an example:

If you expect that "y" will be zero in many cases, it is very inefficient to use exception handling to handle this expected case. Here is the better version:

Exceptions should be used for run-time errors, not normal occurances. This is mostly due to the really time consuming operation of building the stack trace that goes with the exception, which takes a very long time relative to a simple test.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic