2015-04-30 60 views
-1

我試圖會員實例添加到一個種族實例:未處理的異常,不能繼續

  race2.joinJunior(jmem); 
      race2.joinJunior(jmem2); 
      race2.joinJunior(jmem3); 

比賽對象(RACE2)的實例有兩個變量影響下面的代碼,首先是CurrentRunners (目前在參加比賽的運動員)和limitRace(車手允許加入在總比賽的極限)

public override void joinJunior(JuniorMember jm) 
     { 
      junior = jm; 

      if (jm != null) 
      { 
       //Increment the current members on the race by 1. 
       currentRunners++;  

        if (currentRunners > limitRace) 
        { 

         throw new Exception(junior.FirstName + " would be this races: " + currentRunners + "th runner. This race can only take: " + limitRace); 

        } 
      } 
      } 

我的問題是,當我添加第三個成員(jmem3)我的計劃就不可能進步,而不是扔例外。

我究竟做錯了什麼?

+0

「我的計劃無法進展」意味着什麼? –

+0

所以你想讓它拋出異常,但它不會進入'if'塊? 'limitRace'什麼值,我認爲'currentRunners'在這個點上是'3'? –

回答

0

您正在拋出if塊的異常。它需要在某個地方處理。我會建議顯示一條消息,而不是例外。

如果你真的想拋出異常,你需要在你的代碼中處理它。

你可以使用這樣的事情:

public override void joinJunior(JuniorMember jm) 
{ 
if(jm != null && currentRunners < limitRace){ 

// Add runner to the list or collection 

currentRunners++; 
} 
else{ 
// Show message that list of runners is full. This will require you to change the return type of your method or add out parameters 
} 
} 

如果你去例外:

public override void joinJunior(JuniorMember jm) 
    { 
    if(jm != null && currentRunners < limitRace){ 

    // Add runner to the list or collection 

    currentRunners++; 
    } 
    else{ 
    // throw your own exception type (you will need to create this class) 
    throw new LimitExceededException("Some message here."); 
    } 
    } 

在調用者的方法,你需要這樣的事情:

try{ 
       race2.joinJunior(jmem); 
       race2.joinJunior(jmem2); 
       race2.joinJunior(jmem3); 
    } 
catch(LimitExceededException ex){ 
// handle, replace or rethrow as per your application needs 
} 
+0

沒關係,修正它,沒有處理我的單元測試類中的異常。 –