Share via


Null checking vs try catch

Question

Tuesday, December 23, 2008 10:54 AM

Hi,
 Is null checking for each parameter mandatory?
Or is it better to use the try catch only?
Which one is better in performance?

Which is a good practice among the below code?

Case 1:

string foo(object anyObject)
{
    if(anyObject == null)
    {
        // Log this
        throw new ArgumentNullException();
    }
    // do some operations with anyObject which may cause a null reference exception.
    return anyObject.ToString();
}

Case 2:

string foo(object anyObject)
{
    try
    {
        // do some operations with anyObject which may cause a null reference exception.
        return anyObject.ToString();
    }
    catch(NullReferenceException exception)
    {
        //Log this
        throw new ArgumentNullException();
    }
}

Thanks in advance,
Bold techie

All replies (3)

Tuesday, December 23, 2008 11:01 AM | 1 vote

Definitely number 1. You should also name the failing parameter in the ArgumentNullException - every little bit of info helps! Throwing exceptions is cheap, catching them isn't, so number 2 will be slower. Generally I consider it is bad practice to needlessly catch exceptions. In example 2, you are catching an exception merely to throw another one, which is a bit pointless.


Tuesday, December 23, 2008 11:08 AM | 1 vote

Hi,

Throwing and catching exceptions can be very expensive. Case 2 is expensive.

for more information just have a look 
http://msdn.microsoft.com/en-us/library/ms998549.aspx

http://msdn.microsoft.com/en-us/library/ms973839.aspx


Tuesday, December 23, 2008 11:16 AM

If you are going to throw an exception anyways, I'd say it doesn't really matter, since the exception cost will be there anyways (just a little higher). Exceptions aren't supposed to be part of the normal flow of your program, so if you are going to throw an exception, this is something that is not supposed to happen very often.