Neo
Neo

Reputation: 3399

Is the message attribute of an exception in try catch ever an empty string or NULL?

I cannot find a definitive answer, and well the MS docs are not the greatest so here goes to finding an answer versus being cast into down vote hell.

Consider this simple code:

    try
    {
        if (errMessage.Contains(EXCEPTIONCOMPARISONMESSAGE))
        {
            //do stuff;
        }
    }
    catch (Exception ex)
    {
        eventLog.WriteEntry("isAbleConvertToPDF: " + ex.Message, EventLogEntryType.Error);
    }

My question is will ex.Message ever be an empty string or NULL? I think NOT, but I cannot find a definitive documented answer.

Looking for documentation to back up the answer given too please.

Upvotes: 0

Views: 403

Answers (2)

D Stanley
D Stanley

Reputation: 152556

It's certainly possible - a custom exception (one that inherits from Exception) could return a null or empty string.

The Exception constructor also takes a message as a parameter, which could be an empty string.

There is nothing in the interface contract to indicate that the message can never be empty or null, so you should assume that it could be empty or null.

Here's an example, filling in your example code:

try
{
    if (errMessage.Contains(EXCEPTIONCOMPARISONMESSAGE))
    {
        throw new MyEvilException();
    }
}
catch (Exception ex)
{                                                V--------V this will be null
    eventLog.WriteEntry("isAbleConvertToPDF: " + ex.Message, EventLogEntryType.Error);
}

private class MyEvilException : Exception
{
    public override String Message 
    {
        get 
        {  
            return null;
        }
    }
}

Upvotes: 2

Fabio
Fabio

Reputation: 32445

Exception is base class for other exceptions where Message property is marked as virtual.
Which mean that Message can be empty string or null, because every derived class can override it.

However actual implementation of Message in Exception class looks like

public virtual String Message 
{
    get 
    {  
        if (_message == null) 
        {
            if (_className==null) 
            {
                _className = GetClassName();
            }
            return Environment.GetResourceString("Exception_WasThrown", _className);

        } 
        else 
        {
            return _message;
        }
    }
}

So you can see from above, that null will never be returned from Exception base class, but empty string will be returned when throw new Exception(string.Empty);

Upvotes: 2

Related Questions