tags:

views:

42

answers:

1

I have programmed a sub procedure that will be called in the main procedure (called by mainForm event), to validate the inputs before the main calculation. Now I'm searching for a way to cancel the calculation and refocus the mainForm if some inputs are mismatched. I think it's unnecessary to use the Try-Catch statement to trap the error from calculation because I know its source and it should be prevented for the sake of code performance. Does someone have a solution this?

+1  A: 

If you want to leave a subroutine early you just need to say Return.

Edit.

It sounds like you're calling a method that calls another method. Have the second method return a Boolean indicating whether the input is valid. Something like this:

Public Sub CheckMainForm()
    'First validate the input
    If Not IsInputValid() Then Return
    'Next do the rest of your work
End Sub
Public Function IsInputValid() As Boolean
    'Do input validation, if at anypoint something is wrong return false
    If Not IsNumeric(txtAge.Text) Then Return False
    If Not IsValidEmail(txtEmail.Text) Then Return False
    Return True
End Function
Chris Haas
Hi Chris,i want to do something like that direct from the sub procedure but this can only exit the sub, not the main procedure.Lert Pianapitham
Lert Pianapitham
Ya ... thanks, it's a good solution. But actually i have more Subs that use this valid method. Should i rewrite all of these? or Do i have other solutions?
Lert Pianapitham
The only ways to exit a method is to either Return, Exit or Throw. Throw is fairly expensive and should only be used when you can't continue anymore for one reason or another. You'd have to modify every method with Try/Catch to support this, too. Exit will leave you in an undetermined state and won't pass through to calling methods. So yes, I would recommend returning a Boolean of whether or not input validation was successful.
Chris Haas