简体   繁体   中英

NullReferenceException not caught in the catch Block (Array.Sort Method)

try
{
    Array.Sort(PokeArray, (x1, x2) => x1.Name.CompareTo(x2.Name));
}
catch (NullReferenceException R)
{
    throw R;
}

This is a simple line of code that sorts an array of objects I created, however; If there is a null value , it throws an exception. The try catch block does not seem to work.

The exception occurs in this particular area x1.Name.CompareTo(x2.Name) , is the Catch block misplaced?

Thanks!

Update: Screenshot taken from comment below: 在此处输入图片说明

Nope, looks fine. But you are rethrowing the exception after you have caught it; Throw R means that the exception is passed on to the block of code where your try-catch was called from initially.

try
{
    Array.Sort(PokeArray, (x1, x2) => x1.Name.CompareTo(x2.Name));
}
catch (NullReferenceException R)
{
    // throw R; // Remove this, and your exception will be "swallowed". 

    // Your should do something else here to handle the error!
}

Update

First of all, add your screen-shot link to the original post - it helps clarify your problem. :)

Secondly, your try-catch does catch the exception - just not while you are in debug mode. If you continue stepping after that line, you should be able to continue out of the try-catch clause, and you program should continue.

If your exception was not caught, it would have terminated the program.

PS : Select Debug and Exceptions.. from the main menu in VS, and make sure you don't have "Thrown" checked for any column - if you do, your program will pause and display any exception that occurs, instead of just "swallowing" them as it would otherwise.

Let repeat this, just to be absolutely clear: This exception is only visible because the code is running in debug mode with exceptions viewing enabled.

If the same code ran in production mode, the exception would be swallowed, just as the OP expects.

In your case, the code won't throw NullReferenceException since the NullReferenceException is been swallowed by the default implementation of Compare method when you call Array.Sort() . And this exception is propagated as InvalidOperationException down the line. This is why your NullReferenceException catch block skipped. You can reproduce the whole scenario with following simple example where I purposefully including null as collection element.

public class ReverseComparer : IComparer<string>
{
    public int Compare(string x, string y)
    {
     return y.CompareTo(x); //Here the logic will crash since trying to compare with   null value and hence throw NullReferenceException
    }
}

public class Example
{
    public static void Main()
    {
        string[] dinosaurs =
            {
               "Amargasaurus",
                null,
                "Mamenchisaurus",

            };

        Console.WriteLine();
        foreach (string dinosaur in dinosaurs)
        {
            Console.WriteLine(dinosaur);
        }

        ReverseComparer rc = new ReverseComparer();

        Console.WriteLine("\nSort");
        try
        {
            Array.Sort(dinosaurs, rc); //Out from here the NullReferenceException propagated as InvalidOperationException.
        }
        catch (Exception)
        {

            throw;
        }

    }
}

You could just make your code handle nulls better. Eg if all of the values could be null, this should cover you:

if (PokeArray != null)
    Array.Sort(PokeArray, (x1, x2) =>
      string.Compare(x1 != null ? x1.Name : null, x2 != null ? x2.Name : null));

If you don't expect some of those values to ever be null, you can make the code simpler by removing the unnecessary null checks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM