无法捕获 NullReferenceException

moj*_*ojo 1 c# exception-handling

第一次在这里发帖,很抱歉,如果我弄错了一些细节。我正在尝试捕获用户输入无效(不存在)员工的异常。我尝试了许多不同的变体,但从未出现错误。相反,代码只是终止,在这种情况下,它将在以下几行之后退出:

 MyPostSalary = Convert.ToDouble(Console.ReadLine());
 Console.WriteLine();
Run Code Online (Sandbox Code Playgroud)

谁能看到我做错了什么?

完整代码:

       Console.Write("Employee ID: ");
        myEID = Console.ReadLine();

        try
        {
            Console.Write("Post ID: ");
            myPID = Console.ReadLine();

            if ((myEmployees[myEID] is MonthlyPaidEmployee) || (myEmployees[myEID] isWeeklyPaidEmployee))
            {

                Console.Write("Post Name: ");
                MyPostName = Console.ReadLine();
                Console.Write("Post Start Date: ");
                MyPostStartDate = Convert.ToDateTime(Console.ReadLine());
                Console.Write("Post End Date: ");
                MyPostEndDate = Convert.ToDateTime(Console.ReadLine());
                Console.Write("Post Salary: ");
                MyPostSalary = Convert.ToDouble(Console.ReadLine());
                Console.WriteLine();

                myPost = new Post(myPID, MyPostName, MyPostStartDate, MyPostEndDate, MyPostSalary);

                if (myEmployees[myEID] is MonthlyPaidEmployee)
                {
                    myMonthlyEmp = (MonthlyPaidEmployee)myEmployees[myEID];
                    myMonthlyEmp.PostHistory.Add(myPID, myPost);
                }

                if (myEmployees[myEID] is WeeklyPaidEmployee)
                {
                    myWeeklyEmp = (WeeklyPaidEmployee)myEmployees[myEID];
                    myWeeklyEmp.WeeklyPaidEmployeePostHistory.Add(myPID, myPost);
                }

            }

        }
        catch (NullReferenceException ex)
        {

            Console.WriteLine("Employee ID does not exist.");
            Console.WriteLine(ex.Message);
            Console.WriteLine();
            Console.WriteLine("Press any key to continue");
            Console.ReadLine();

        }
Run Code Online (Sandbox Code Playgroud)

ted*_*bus 5

您是否在 Visual Studio(或您的 IDE)上进行调试?如果是,则可能您正在捕获异常,但 IDE 设置为在引发异常时显示警告消息...尝试在 IDE 之外运行您的应用程序,如果它有效,您可以在 NullReferenceExceptions 引发时禁用警告,但它是相当危险。为此,请在 Visual Studio 中查找“异常设置”(或类似的内容,我不确定,因为我使用意大利语版本)。