使用Throw Catch OO WPF进行简单修复

时间:2015-05-05 00:02:58

标签: c# wpf oop try-catch

场合

我遇到了try catch问题在OO WPF应用程序中,我正在开发允许不同类型的成员加入Races。

问题

为了解释我的问题,我试图通过以下代码让会员参加比赛:

race.joinJunior((JuniorMember)hillracing.searchMembers(Username));

因此,JuniorMember(使用searchMember方法和预先存在的Username参数找到了对象)将通过joinJunior方法作为Junior成员加入比赛。

这段代码本身不是问题所在,但确实会导致它,因为它调用了joinJunior方法,因此存在问题。

public override void joinJunior(JuniorMember jm)
        {
            if (junior != null)
            {
                //Increment the current members on the race by 1.
                currentRunners++;

                if (currentRunners > limitRace)
                {

                    currentRunners = limitRace;

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


                }
            }
            //if the members type doesnt equal the member join permission then they shouldn't be able to join.
            else if (junior.memType != permRace)
            {
                //throws an exception if the member doesn't have the correct type junior
                throw new Exception(senior.FirstName + " does not meet the requirements to join this race, must be type: " + permRace);
            }
            //if the members gender isn't equal to the races gender requirement they shouldn't be able to join that race.
            else if (junior.gender != genRace)
            {
                //throws an exception if the member doesn't have the correct gender type.
                throw new Exception(junior.FirstName + " does not meet the requirements to join this race, must be a: " + genRace);
            }

            else
            {
                //if all other conditions are met, and the member meets requirements, let the member join the race and add a return date of 21 days.
                junior = jm;

                returnDate = DateTime.Today.AddDays(21);
            }
        }

因此,该行出现的问题是具体的。

else if (junior.memType != permRace)
            {
                //throws an exception if the member doesn't have the correct type junior
                throw new Exception(senior.FirstName + " does not meet the requirements to join this race, must be type: " + permRace);
            }

当抛出错误时,它会给出一个异常消息"对象引用未设置为对象的实例"而不是我要求抛出它的例外。你知道,我希望它能抛出这个例外而且这样做是正确的,但它没有提供正确的信息。

我做错了什么?

1 个答案:

答案 0 :(得分:0)

始终检查主要和次要是否为空情况,例如

if ((junior == null) || (junior.memType == null))

然后根据junior经文junior.memType处理错误情况,因为memType可能是一个真正的调试/开发错误,而不是已知的junior