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

Simple fix with Throw Catch OO WPF

情况

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

问题

为了让我的问题通俗易懂,我试图让会员使用以下代码参加比赛:

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

当错误被抛出时,它给出了一个异常消息 "Object reference not set to an instance of an Object" 而不是我要求它抛出的异常。你看,我希望它抛出这个异常,它这样做是对的,但它没有提供正确的消息。

我做错了什么?

始终检查主要和次要的空值情况,例如

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

然后根据 juniorjunior.memType 处理错误情况,因为 memType 可能是一个真正的 debug/development 错误,而不是已知的缺失 junior