dcsimg
When, if ever, do you catch NullPointerException?
2 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Marlon_Cicero
Posted On:   Monday, November 12, 2001 05:31 PM

When, if ever, do you catch NullPointerException? I'm in an argument with my co-worker about how he is dealing with exceptions. There are 52+ fields that could possibly be null and, as good programming practice, should each be checked for null. However, he says that it is too slow to check for nulls and doesn't do it. And, as expected, a null comes up, NullPointerException is thrown, and the entire app crashes. I recommend that he either tests each field for null, or catch NullPointerException at the end of the block to avoid crashing the program. He says that you are NEVER supposed to catch any runtime exceptions and recommends that the *preformatted* String data I return to always have spaces between the tokens. So what is the    More>>

When, if ever, do you catch NullPointerException? I'm in an argument with my co-worker about how he is dealing with exceptions.



There are 52+ fields that could possibly be null and, as good programming practice, should each be checked for null. However, he says that it is too slow to check for nulls and doesn't do it. And, as expected, a null comes up, NullPointerException is thrown, and the entire app crashes.



I recommend that he either tests each field for null, or catch NullPointerException at the end of the block to avoid crashing the program. He says that you are NEVER supposed to catch any runtime exceptions and recommends that the *preformatted* String data I return to always have spaces between the tokens.



So what is the proper way to handle the nulls in this situation?

   <<Less

Re: When, if ever, do you catch NullPointerException?

Posted By:   Christopher_Schultz  
Posted On:   Wednesday, November 14, 2001 08:53 AM

I agree with your friend who says not to catch the NPE. In general, it's in bad form to catch RuntimeExceptions, but not always.



A good example is NumberFormatException. This exception is a RuntimeException because it would be cumbersome to write try{}catch{} blocks around everywhere that calls a method that throws that type of Exception.



Anyway, you certainly should not be catching NullPointerException. You should take better care to prevent NPEs from occurring by first checking their values against NULL and perhaps throwing a more application-specific exception, or IllegalArgumentException.



If the objects are NULL and they aren't supposed to be, then it's an application problem, not an execution problem, and you'll probably want to application to bomb with an NPE.



Just my two cents,

-chris

Re: When, if ever, do you catch NullPointerException?

Posted By:   paresh_bhatia  
Posted On:   Monday, November 12, 2001 11:04 PM

using catch is good option i dont see any harm is using that
About | Sitemap | Contact