我试图将成员实例添加到Race实例:
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块中抛出异常。它需要在某处处理。我建议显示一条消息而不是异常。
如果你真的想抛出异常,你需要在你的代码中处理它。
您可以使用以下内容:
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
}