Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Exception Handling...For Marty Hall..and All

 
Mishra Anshu
Ranch Hand
Posts: 224
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Instead of handling exceptions in our code and then calling sendError(), we can define error pages in the deployment descriptor and then the rest of the headache is handled by the container after making the required mapping for the exception classes and the corresponding error codes. Then, why should one ever use the first approach to handle the exception? :roll:
 
Pradeep bhatt
Ranch Hand
Posts: 8927
Firefox Browser Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The sendError accepts a error code which means somethiing. For Example 404 means Page Not Found whereas an excpetion is an abnormal condition which occurs during the execution of a program.
 
Marty Hall
Author
Ranch Hand
Posts: 111
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Instead of handling exceptions in our code and then calling sendError(), we can define error pages in the deployment descriptor and then the rest of the headache is handled by the container after making the required mapping for the exception classes and the corresponding error codes. Then, why should one ever use the first approach to handle the exception?

You use reponse.sendError to send a particular HTTP status code to the client. In particular, you can send a 404 status code along with a Web page explaining why the page could not be found (e.g., that the request failed to provide the information needed to do a redirect, or some such).
You can indeed use error-page and error-code in web.xml to create Web-application-wide 404 pages. This is most definitely a good idea, but is different than using response.sendError for a page-specific 404 error page.
However, IMHO the idea of using error-page and exception-type to provide error pages for uncaught Java exceptions is not a very good one. There are two reasons why I am very dubious about this idea except as a warning for developers (eg for NullPointException) during initial development:
  • The error page is too general: it cannot fix the specific problems. Instead, plan ahead for missing and malformed data, use try/catch blocks and never have uncaught exceptions! For example, always check that an HTTP request header is non-null before calling a method on the value, and always catch NumberFormatException when doing Integer.parseInt on user-supplied values.
  • If the error occurs far down in the page, the response might already have been committed, and it is too late to transfer to an error page.


  • Cheers-
    - Marty
     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic