繁体   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;
}

然而,这是一行简单的代码,用于对我创建的对象数组进行排序; 如果有空值,则抛出异常。 try catch块似乎不起作用。

异常发生在这个特定区域x1.Name.CompareTo(x2.Name) ,Catch 块是否放错了位置?

谢谢!

更新:截取自以下评论的截图: 在此处输入图片说明

不,看起来不错。 重新抛出异常你抓了之后; 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!
}

更新

首先,将您的屏幕截图链接添加到原始帖子 - 它有助于澄清您的问题。 :)

其次,您的try-catch确实会捕获异常 - 只是在您处于调试模式时不会。 如果在该行之后继续步进,您应该能够继续退出 try-catch 子句,并且您的程序应该继续。

如果您的异常没有被捕获,它就会终止程序。

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

让我们重复一遍,只是为了绝对清楚:这个异常是可见的,因为代码在调试模式下运行并启用了异常查看。

如果相同的代码在生产模式下运行,则异常将被吞下,正如 OP 所期望的那样。

在您的情况下,代码不会抛出NullReferenceException因为NullReferenceException在您调用Array.Sort()时被Compare方法的默认实现所吞噬。 此异常将作为InvalidOperationException向下传播。 这就是跳过NullReferenceException捕获块的原因。 您可以使用以下简单示例重现整个场景,其中我有意将 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;
        }

    }
}

你可以让你的代码更好地处理空值。 例如,如果所有值都可以为空,这应该涵盖您:

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

如果您不希望其中一些值永远为空,则可以通过删除不必要的空检查来简化代码。

暂无
暂无

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

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