File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Servlets and the fly likes How to work with try-catch in servlets Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "How to work with try-catch in servlets" Watch "How to work with try-catch in servlets" New topic
Author

How to work with try-catch in servlets

Andres Gonzalez
Ranch Hand

Joined: Nov 27, 2001
Posts: 1561
Hi. Hi have a servlet that performs different operations, including database access. At the moment I have several try-catch block statements.
when I get an exception, I redirect it to error.jsp, which is an error page, for display purposes.
My question is, should I have a single big try-catch block or should I leave it the way I have it, with small blocks. Which one is better?
thanks


I'm not going to be a Rock Star. I'm going to be a LEGEND! --Freddie Mercury
Colin Humber
Greenhorn

Joined: Nov 05, 2001
Posts: 6
My suggestion would be (in case you haven't already) to create specific method for each operation you wish to perform. i.e one for Database Access. Also have a controller method which makes the appropriate method calls.
Declare all of you "worker" methods to throw their respective Exceptions, and in the controller method wrap your method calls in one try/catch.
Cheers


Sun Certified Programmer for the Java 2 Platform.<br />Sun Certified Programmer for the Java 2 Platform, 1.4.<br />Sun Certified Web Component Developer<br />IBM Certified Specialist VisualAge for Java.<br />IBM Certified Solution Developer (OOAD w/ UML).
Bruce Jin
Ranch Hand

Joined: Sep 20, 2001
Posts: 671
This suggestion sounds good.
Is it recommended in general Java programming?
Does anybody have other ideas?
Thanks.


BJ - SCJP and SCWCD
We love Java programming. It is contagious, very cool, and lot of fun. - Peter Coad, Java Design

Crazy Bikes created by m-Power
William Brogden
Author and all-around good cowpoke
Rancher

Joined: Mar 22, 2000
Posts: 12835
    
    5
Note that some exceptions have specific information that can only be useful if you catch the specific exception and extract the data. For example, I use this in a method that has to parse an XML file.

As you can see, in the case of an SAXParseException it extracts data pointing to the exact line.
Note that your error.jsp can do instanceof tests on the exception object and extract the same sort of information.
Bill
Bruce Jin
Ranch Hand

Joined: Sep 20, 2001
Posts: 671
Thanks Bill for the explaination.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How to work with try-catch in servlets