This week's giveaway is in the Spring forum.
We're giving away four copies of Learn Spring Security (video course) and have Eugen Paraschiv on-line!
See this thread for details.
Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to work with try-catch in servlets

 
Andres Gonzalez
Ranch Hand
Posts: 1561
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Colin Humber
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Bruce Jin
Ranch Hand
Posts: 672
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This suggestion sounds good.
Is it recommended in general Java programming?
Does anybody have other ideas?
Thanks.
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13055
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 672
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Bill for the explaination.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic