lost_in_the_source
lost_in_the_source

Reputation: 11237

How to stop exception

How do I prevent the program from going into the try-catch blocks if I cancel something? Ex:

try{
  int i=int.Parse(Interaction.InputBox("BlahBlahBlah"));
}
catch{
  //error handling
  return
}

But what if I press "Cancel" or the X on the top? It goes to the try-catch, and considers this an exception. So it does the error handling. How do I stop this?

Upvotes: 0

Views: 120

Answers (1)

Dai
Dai

Reputation: 154995

According to the documentation ( http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.interaction.inputbox(v=vs.110).aspx ) an empty string is returned if the user cancels.

You'll want this:

do {
    String text = Interaction.InputBox("Enter a number");
    if( text == "" ) return -1;
    Int32 number;
    if( Int32.TryParse( text, out number ) ) return number;
} while( true );

This way it will keep on prompting the user until a valid integer number is entered or they Cancel the dialog.

Upvotes: 3

Related Questions