Try & Catch dosent work with "Task"

Carlo Goretti 121 Reputation points
2021-04-29T11:25:39.753+00:00

Hey,

I have this method that checks if a Task scheduler exists or not....
It have Worked before but now the Try & catch dosent "Catch" the error...

 public void TaskSchedulerLogg()
        {

            try
            {
                var taskName = config.AppSettings.Settings["SchemaLäggareNamnFavorit"].Value;
                var task = ts.GetTask(taskName);


                counter = (int)(Convert.ToDateTime(task.NextRunTime.ToString()) - DateTime.Now).TotalSeconds;
                timeSpan = TimeSpan.FromSeconds((int)(Convert.ToDateTime(task.NextRunTime.ToString()) - DateTime.Now).TotalSeconds);

                Tid_FöregåendeLbl.Text = task.LastRunTime.ToString().ToString();

                if (NedräkningsTimer.Enabled == false)
                {
                    NedräkningsTimer.Start();

                }
                Tid_Nästa.Text = timeSpan.ToString(@"hh\:mm\:ss");


                if (task.IsActive == true)
                {
                    Status.Text = "Aktiverad";
                    pictureBox1.Image = Resources.GreenPicture;
                }
                else
                {
                    Status.Text = "Inaktiverad";
                    pictureBox1.Image = Resources.Gul;
                }


                SchemaläggareInfoBtn.Visible = false;
                KonfigurationBtn.Location = SchemaläggareInfoBtn.Location;

            }
            catch
            {
                Tid_FöregåendeLbl.Text = "ERROR";
                Tid_Nästa.Text = "ERROR";
                Status.Text = "ERROR";
                SchemaläggareInfoBtn.Visible = true;
                KonfigurationBtn.Location = OldPosKonfigurationBtn;
                NedräkningsTimer.Stop();
                pictureBox1.Image = Resources.RedPicture;
            }
        }

Im happy for some input.
Thanks!

Developer technologies | Windows Forms
Developer technologies | C#
{count} votes

Accepted answer
  1. Viorel 122.6K Reputation points
    2021-04-30T12:43:47.39+00:00

    It seems that the system behaves as expected, i.e. ts.GetTask returns null for inexistent tasks, however the subsequent NullPointerException is intercepted by Debugger. If you press <F5> to continue execution, or start the program without debugging using <Ctrl+F5>, then the catch block will be reached.

    You can also uncheck the shown “Break when this exception type is thrown” checkbox (or adjust the settings in menu, Debug, Windows, Exception Settings window). Then this kind of exceptions will not be intercepted by Visual Studio during debugging.

    It is probably better to add some ‘if(task==null)’ and display an appropriate message.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.