简体   繁体   English

NullReferenceException 未在 catch 块中捕获(Array.Sort 方法)

[英]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. try catch块似乎不起作用。

The exception occurs in this particular area x1.Name.CompareTo(x2.Name) , is the Catch block misplaced?异常发生在这个特定区域x1.Name.CompareTo(x2.Name) ,Catch 块是否放错了位置?

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. Throw R意味着异常被传递到最初调用 try-catch 的代码块。

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.其次,您的try-catch确实会捕获异常 - 只是在您处于调试模式时不会。 If you continue stepping after that line, you should be able to continue out of the try-catch clause, and you program should continue.如果在该行之后继续步进,您应该能够继续退出 try-catch 子句,并且您的程序应该继续。

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. PS :从 VS 的主菜单中选择Debug and Exceptions.. ,并确保您没有为任何列检查“Thrown”——如果这样做,您的程序将暂停并显示发生的任何异常,而不仅仅是“吞下”它们,否则会发生。

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.如果相同的代码在生产模式下运行,则异常将被吞下,正如 OP 所期望的那样。

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() .在您的情况下,代码不会抛出NullReferenceException因为NullReferenceException在您调用Array.Sort()时被Compare方法的默认实现所吞噬。 And this exception is propagated as InvalidOperationException down the line.此异常将作为InvalidOperationException向下传播。 This is why your NullReferenceException catch block skipped.这就是跳过NullReferenceException捕获块的原因。 You can reproduce the whole scenario with following simple example where I purposefully including null as collection element.您可以使用以下简单示例重现整个场景,其中我有意将 null 作为集合元素。

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.如果您不希望其中一些值永远为空,则可以通过删除不必要的空检查来简化代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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