wood burning stoves 2.0*
The moose likes Servlets and the fly likes Do you have elegant way of nullpointer exceptions Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "Do you have elegant way of nullpointer exceptions " Watch "Do you have elegant way of nullpointer exceptions " New topic
Author

Do you have elegant way of nullpointer exceptions

Jean Miles
Ranch Hand

Joined: Aug 20, 2003
Posts: 53
in JSP or servlet?
Pradeep bhatt
Ranch Hand

Joined: Feb 27, 2002
Posts: 8919

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.


Groovy
Tim Baker
Ranch Hand

Joined: Oct 04, 2003
Posts: 541
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 ?


Kim Jong II (North Korea's Dear Leader) said:Nuclear weapons don't kill people, people kill people.
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

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.


[Jess in Action][AskingGoodQuestions]
Jean Miles
Ranch Hand

Joined: Aug 20, 2003
Posts: 53
Thanks that helps. we should avoid runtime exceptions and if they do happen how they should be handled.
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
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/


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Do you have elegant way of nullpointer exceptions