问题
I recently made the statement to a colleague that:
NullReferenceExceptions should never be explicitly caught
I used the word never.... hmmm. I've never seen a appropriate use case myself for catching them but I wanted to check if anyone else has?
Never is such a strong word after all.....
回答1:
It depends on why; see Eric Lippert's blog entry. If they are "boneheaded exceptions", then no - just fix the calling code. In the rare case that they are "vexing exceptions" (i.e. the code you are calling has traps that are hard to avoid), then I guess you'd have to.
回答2:
Well, when you call into a buggy third party library which ocasionnaly causes nullrefs, it's probably a good idea to catch them if you know how to properly deal with them.
Real-life example : In the past, I've used quite extensively a datagrid provided by a third party editor. They have (or had at this time) a confirmed bug which whould throw a nullref (nested deep in their call stack) from time to times when updating some data in the underlying data source.
I've dealt with the situation with this code :
try
{
// do the update
}
catch (NullReferenceException)
{
try
{
// redo the update
}
catch (NullReferenceException ex)
{
// properly log the third party lib failure
}
}
Btw, my "log" code has never executed in 2 years:) Now the third party editor has fixed the issue, and I should probably remove this code.
回答3:
Maybe the correct quote is
NullReferenceExceptions should never be explicitly caught if you own the code which thrown the Exception
回答4:
You're right, "never" is a strong word.
Catching a NullReferenceException (or an NPE for Java), will always depend on the purpose of the code.
For instance, if your application REQUIRES that processing continue even with potentially uncertain state (think life support systems) or if your code doesn't care about the state of the referenced object (ex: batch processing data that throws out, literally, bad data).
It's a good rule of thumb to not catch these types of exceptions, but not a law.
回答5:
I wouldn't say never. For instance you could catch it to log the exception or to marshal it from one thread to another. In both cases the exception should be throw again.
As Marc Gravell points out Eric Lippert has a very good entry on his blog about exceptions.
回答6:
I once had to build a big string based on the values of 15 or so variables. Instead of checking each one for nullness, I simply went on and created the string, dereferencing the variables, and catching the NRE. To be honest it felt bad and naughty, but it saved me from writing a lot of code.
来源:https://stackoverflow.com/questions/585480/should-nullrefs-ever-be-caught