Search code examples
c#.netservice-referencetimeoutexception

TimeoutException is null when thrown


How is it possible that thrown TimeoutException object is null and it throws

Object reference not set to an instance of an object.

in following line:

writeToLog(e2.ToString());

Check out this code.

WebServiceRef.CallResponse callResponse = null;
try
{
    callResponse = webServiceClient.Call(callRequest);
}
catch (TimeoutException e)
{
    try
    {
        WebServiceRef.CallStatusResponse callStatusResponse = webServiceClient.CallStatus(callStatusRequest);
        if (callStatusResponse.ResponseCode != 0)
        {
            throw new Exception("nok: " + callResponse.ResponseCode);
        }
    }
    catch (TimeoutException e2)
    {
        writeToLog(e2.ToString());
    }
}  

This is my writeToLog method.

private static void writeToLog(String logMsg)
{
    using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"log.txt", true))
    {
        file.WriteLine(DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss ") + logMsg);
    }
}

Stacktrace and message is this:

Object reference not set to an instance of an object.
 at ...(...) in c:\...cs:line 82
 at ...(...) in c:\...cs:line 193

Line 82 is point at

writeToLog(e2.ToString());


Solution

  • There is no way a null Exception instance can be thrown / caught.

    Either something must be wrong with your debug symbols or you're not running the correct program. Try logging some test strings here and there to make sure the correct code is executed:

    //...
    catch (TimeoutException e2)
    {
        Debug.WriteLine("If you don't see this in the output window then somehow you are not running this app.");
        writeToLog(e2.ToString());
    }
    //...