Search This Blog

Showing posts with label exceptions. Show all posts
Showing posts with label exceptions. Show all posts

Thursday, April 17, 2008

How you will handle errors and exceptions in Struts?

An efficient error and exception handling makes an application behave gracefully under abnormal conditions.Struts has errors and exception handling done in different ways.The form validations using Struts require a proper mechanism.For handling errors in Struts,it has two objects ActionError and ActionErrors.Whenever a form is submitted then cotroller receives request and then create ActionForm object which calls reset() method and stores ActionForm object to required scope and then it loads ActionForm object from request and calls validate() method.If validate method fails then errors are displayed on the form itself through html:errors tags.
Exception Handling can be done in following ways:

-try-catch block within -Using declarative exception handling.In struts-config.xml we can declare on which type of exception, a request should be redirected to.Use Global Exceptions tag in struts-config.xml

global-exceptions

"<"exception key="errors.MyException" type="java.lang.MyException" path="/myExcption.jsp"/ ">"

So whenever MyException occurs then Struts framework will display 'myException.jsp' page.The interpretation of this is that if MyException is caught by Struts' ActionServlet then it should redirect to myExcption.jsp. The key is as usual a pointer to the message resource file.


Saturday, March 22, 2008

Why is it not advisable to catch type “Exception”?

Exception handling in Java is polymorphic in nature. For example if you catch type Exception in your code then it can catch or throw its descendent types like IOException as well. So if you catch the type Exception before the type IOException then the type Exception block will catch the entire exceptions and type IOException block is never reached. In order to catch the type IOException and handle it differently to type Exception, IOException should be caught first (remember that you can’t have a bigger basket above a smaller basket). The diagram below is an example for illustration only. In practice it is not recommended to catch type “Exception”. We should only catch specific subtypes of the Exception class. Having a bigger basket (i.e. Exception) will hide or cause problems. Since the RunTimeException is a subtype of Exception, catching the type Exception will catch all the run time exceptions (like NullpointerException, ArrayIndexOut-OfBounds-Exception) as well.