System.NullReferenceException Not Being Caught in First Try/Catch Block

10,129

Solution 1

It doesn't bypass anything. Look closely at your stack trace. Use Console.WriteLine(ex.ToString());. You'll see that the exception is not being thrown from where you thought it was.

Solution 2

This simply isn't the case and here's the proof:

class Program
{
    static void Main()
    {
        // no need of try/catch here as exceptions won't propagate to here
        Looper();
    }

    static void Looper()
    {
        int processedRecords = 0;
        for (int i = 0; i < 10; i++)
        {
            try
            {
                Thrower(i);
                processedRecords++;
            }
            catch (NullReferenceException ex)
            { }
        }
        // prints 5 as expected
        Console.WriteLine("processed {0} records", processedRecords);
    }

    static void Thrower(int i)
    {
        if (i % 2 == 0)
        {
            throw new NullReferenceException();
        }
    }
}
Share:
10,129
rgeorge
Author by

rgeorge

Updated on June 06, 2022

Comments

  • rgeorge
    rgeorge almost 2 years

    I have a C# Console app that starts in 'static int Main(string[] args)', creates an instance of 'EventRecievedProcessor' class and then calls a method on the instance:

    static int Main(string[] args)
    {
        try
        {
            EventRecievedProcessor proc = new EventRecievedProcessor
    
            if (!proc.Processs())
            {
                Console.Write(Type + "  processing failed.  Please check logs for more information.");
                Log.Error("Failed to process s");
                return (int)RETURNCODES.INTERNALAPPERROR;
            }
        }
        catch (Exception ex)
        {
            // This is where the System.NullReferenceException from GetLatestEventInfo is currently being caught
    
            Console.WriteLine("Exception message: " + ex.Message);
            Console.WriteLine("Exception stack trace: " + ex.StackTrace);
    
            Log.Fatal("An exception has been thrown. Message: " + ex.Message, ex);
    
            return (int)RETURNCODES.INTERNALAPPERROR;
        }
    }
    

    The instance of 'EventRecievedProcessor' grabs a collection of records and does a foreach over it. It calls a static method (GetLatestEventInfo) on the 'Event' class for each record in the collection:

    public class EventRecievedProcessor
    {
    
        public bool Processs()
        { 
            List<Event> events = DAL.GetEvents;
    
            foreach (Event e in events)
           {
                try
                {
                    EventInfo lastEvent = Eventhistory.GetLatestEventInfo(e);
                }
                catch (Exception ex)
                {
                    // Log exception and continue processing in foreach loop
    
                    // This is where I want to catch the NullReferenceException from GetLatestEventInfo
    
                    Log.DebugFormat("Error with eventid " + e.EventID);
                    Log.Error(ex);
                }
            } 
    
            return true;
        }
    }
    

    When the follwoing method is called, a System.NullReferenceException is thrown:

    public class EventHistory
    {
    
        public static EventInfo GetLatestEventInfo(int customerCode, string premiscode)
        {
    
            EventInfo info = new EventInfo();
    
            // Do some work here...
            // This is where the NullReferenceException is being generated.
    
            return info; 
    
        }
    }
    

    When the NullReferenceException is thrown here, I would expect the catch block in the foreach loop to catch it, log it, and then return control to the foreach loop to continue processing. Instead, the exception is being caught in the top level 'Main' method, which means the app aborts and the remaining records are not processed.

    I'm at loss as to how/why the exception bypasses the first catch block. Any ideas on what I'm doing wrong here?

    Adding the stack trace:

    System.NullReferenceException: Object reference not set to an instance of an object. at EventProcessor.EventHistory.GetLatestEventInfo(Event e) in C:\Dev\release6.01.100\Events\EventProcessor\EventProcessor\EventHistory.cs:line 65 at EventProcessor.Processors.EventProcessor.Process() in C:\Dev\release6.01.100\Events\EventProcessor\EventProcessor\Processors\EventProcessor.cs:line 32 at EventProcessor.Program.Main(String[] args) in C:\Dev\release6.01.100\Events\EventProcessor\EventProcessor\Program.cs:line 132

    Sorry if I've munched some of the names. This is work code, so I tried to change it up a little to avoid any privacy conflicts.