2013-10-25 51 views
1
try 
{ 
    Array.Sort(PokeArray, (x1, x2) => x1.Name.CompareTo(x2.Name)); 
} 
catch (NullReferenceException R) 
{ 
    throw R; 
} 

這是一個簡單的代碼行,它對我創建的對象數組進行排序;如果存在空值,則會引發異常。 try catch塊似乎不起作用。NullReferenceException未捕獲到catch塊(Array.Sort方法)

在這個特定區域發生異常x1.Name.CompareTo(x2.Name),Catch塊是否放錯了位置?

謝謝!

+1

如果你想捕捉一個異常並重新拋出它,你應該__always__使用'throw;'而不是'throw ex;'來避免丟失異常的原始堆棧跟蹤。 –

+0

感謝您的快速回復,我只使用thow,它似乎仍然給我同樣的錯誤突出顯示相同的區域是這樣的:「x1.Name.CompareTo(x2.Name)」說NullReferenceException沒有被捕獲,謝謝! –

+0

嘗試捕捉一個普通的異常,看看它是否像'catch(Exception ex)'一樣工作'我知道這很糟糕,但只是爲了看到。 – Tafari

回答

3

不,看起來不錯。但你重新拋出異常後,你已經抓住它; 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主菜單中選擇DebugExceptions..,並確保你沒有「時拋出」檢查是否有列 - 如果你這樣做,你的程序將暫停,並顯示發生任何異常,而不是像其他人那樣「吞食」它們。

+0

感謝您的回覆,似乎即使我不重新拋出它,錯誤仍然存​​在。 –

+0

謝謝,但即使這不起作用,這是一個截圖,如果它有幫助:http://i497.photobucket。com/albums/rr333/Dialga1000/NullReferenceExeptionWeird.png –

+0

它如何持續?如果它是'NullReferenceException',它應該被捕獲。如果沒有,請檢查該異常是否屬於該類型。這仍然不能解決你原來的邏輯錯誤 - 只是「吞下」(隱藏)錯誤。您最好先解決原始問題:刪除(或忽略)包含'null'的對象。 – Kjartan

0

在你的情況下,由於NullReferenceException是被Compare方法的默認實現吞噬,當你調用Array.Sort()的代碼不會拋出NullReferenceException。這個異常傳播爲InvalidOperationException下線。這就是爲什麼你的NullReferenceException catch塊跳過。您可以通過以下簡單示例重現整個場景,其中我有目的地將null包含爲collection元素。

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

    } 
} 
+0

在catch塊中使用「Exception」似乎現在工作,但現在名稱以「C」後的任何字母開頭,在數據結構中輸入的最後一個名稱是「Chespin」,之後的所有名稱都未填充到通過此數組填充的列表框中,謝謝! –

0

你可以讓你的代碼更好地處理空值。例如。如果所有的值可能是零,這應包括您:

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

如果你不希望其中的一些價值觀永遠爲空,可以通過刪除不必要的null檢查使代碼更簡單。

+0

謝謝,這似乎消除了錯誤,但是,我填充使用此數組的列表框似乎現在爲空(使用「名稱」成員填充它),我的數據結構是這樣的,我可以保證沒有空值,甚至使其工作,但我只是好奇,如果我不知道什麼時候或哪裏會出現空值,我會怎麼做。 –

相關問題