File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
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

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?

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

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.

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: 672
This suggestion sounds good.
Is it recommended in general Java programming?
Does anybody have other ideas?

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

Joined: Mar 22, 2000
Posts: 13036
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.
Bruce Jin
Ranch Hand

Joined: Sep 20, 2001
Posts: 672
Thanks Bill for the explaination.
I agree. Here's the link:
subject: How to work with try-catch in servlets
It's not a secret anymore!