[英]NullReferenceException not caught in the catch Block (Array.Sort Method)
不,看起來不錯。 但你重新拋出異常你抓了之后; 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
andExceptions..
,並確保您沒有為任何列檢查“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.