This is specific to .NET I am writing a code piece where I have to use catch all exception handler. I call a series of function which may return null. I do not want to continue if any of them return null as I have an alternate but costly method to get the same result. I want to know if I should be using the series of null checks or not. My code looks something like:
var some_info = null;
try{
var a = GetA();
if(a != null){
var b = a.GetB();
if(b != null){
var c = GetC(b);
if(c != null){
some_info = c.GetSomeInfo();
}
}
}
catch(Exception e){
// cant do anything here but I need above code to be silent
}
if(some_info == null)
some_info = GetSomeInfoFromHeavyMethod();
in C# if we try to use null reference it throws an exception so if any of the variables above will be null a NullReferenceException will be thrown. Therefore we can write the above code like
var some_info = null;
try{
var a = GetA();
var b = a.GetB();
var c = GetC(b);
some_info = c.GetSomeInfo();
}
catch(Exception e){
// cant do anything here but I need above code to be silent
}
if(some_info == null)
some_info = GetSomeInfoFromHeavyMethod();
My question is, should I use null checks here or let exception handler work here? My gut feeling says I should use the null check as it is good practice but, I have a doubt as I have to use catch all exception handler here and I already have to bear cost of try/catch block.
Yes, I would strongly advise using null checks:
NullReferenceException
due to just not doing checksUltimately, I'd consider every NullReferenceException
to be a bug somewhere - it's the kind of exception that should always cause you to either add more validation (e.g. to throw ArgumentNullException
) or handle the value being null. That wouldn't the case in your code.
With some refactoring you may be able to use the null-conditional operator introduced in C# 6 to reduce the code though. You might end up with:
someInfo = GetA()?.GetB()?.GetC()?.GetSomeInfo();
See more on this question at Stackoverflow