vendredi 13 novembre 2020

Catching an Exception with try-catch inside an if/switch block

I'm trying to catch a nullReferenceException within an if statement that is inside a switch statement... I've tried a number of different ways but I can't get the error to actually catch, it just keeps causing crashes.

               try 
                {
                switch (selectedOption)
                {

                    case "1":
                        break;
                    case "2":
                        if (textBox1.Text == "TEXT")
                        {
                            MessaageBox.Show("TEXT")
                        }
                        else
                        {
                            MessageBox.Show("ELSETEXT")
                        }
                        throw new Exception;
                    case "3":
                        break;
                     default:
                        break;
                 }
               }
              catch (Exception)
                  {
                     MessageBox.Show("An error has occured");
                  }

I'm getting a null reference exception on case 2 at if textbox1 == text, when there is no value, I'd like to catch that null reference and display a message.

Thanks for any help/advice!

Aucun commentaire:

Enregistrer un commentaire