File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Do you have elegant way of nullpointer exceptions

 
Jean Miles
Ranch Hand
Posts: 53
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
in JSP or servlet?
 
Pradeep bhatt
Ranch Hand
Posts: 8927
Firefox Browser Java Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can use an Error page to display the error if it occurs in JSP.
In servlets you can make an entry in the web.xml and map the exception to some error page.
 
Tim Baker
Ranch Hand
Posts: 541
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i find with nullpointers it's normally best to check variables against null before you use them
if(a != null)
a.something();
else
out.print("some error");
there are so many different nulls that can occur in one program i don't think a single page will be that helpful ?
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24204
34
Chrome Eclipse IDE Mac OS X
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I agree with Tim that the most elegant way of daling with NPEs is to not have them in the first place. Anytime an NPE occurs, it's an error in your program.
 
Jean Miles
Ranch Hand
Posts: 53
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks that helps. we should avoid runtime exceptions and if they do happen how they should be handled.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's an ancient practice to return null to indicate some kind of failure or problem, probably dating back to the first days of C. This forces you to check for nulls. But there is a "null object" pattern that you can use. Instead of returning null, return a special instance or subclass of the expected object with the special behavior. Frinstance:

You could change getPage to return a NullPageObject which extends PageObject to always return "" and eliminate the test for null.
Of course this mostly applies to where you are in control of introducing the null pointers in the first place. And it might be a strategy for handling some that are created by code that you cannot change.
Here's an academic discussion ... I just Googled for "null object pattern" http://www.cs.oberlin.edu/~jwalker/nullObjPattern/
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic