SPi01
SPi01

Reputation: 11

Stop running code in Functions

I recently coded a program on VB.NET that shows Input1 Mod Input2 for example. Here i use function :

Private Function remainder(intno1 As Integer, intno2 As Integer) As Integer

    Dim intresult As Integer
    intresult = intno1 Mod intno2
    remainder = intresult

End Function

Then i called it on Button_Click event :

    Dim intm As Integer, intn As Integer
    Dim intmod As Integer
    intm = Val(TextBox1.Text)
    intn = Val(TextBox2.Text)

    If TextBox1.Text >= TextBox2.Text Then
        MsgBox("Error while computing proccess ! Please try Again.", vbOKOnly + vbCritical, "Error!")
        **Stop statement**
    End If
    intmod = remainder(intm, intn)
    RichTextBox1.Text = "The result is " & Str(intmod) 

as you can see on this code, i use if statements when txt1 is bigger or equals txt2 then message box shows. before End If clause i want to use statement that stop running the code. i mean stop doing those process on Function.

I use Stop and End statements but after i debug the program, it stop responding or even exit the program.

What should i do exactly here ?

Upvotes: 1

Views: 4954

Answers (3)

dovid
dovid

Reputation: 6462

when you want exit from a function without return any value, It shows the software failure , and must not give the impression of 'business as usual' to the responsible caller code.

for this you need Throw an exception:

Throw New Exception("Error while computing proccess ! Please try Again.")

in this case the exception its not a suprise, it is likely command will be executed inadvertentlyexecuted inadvertently when the input text-boxes not correspond to expectations. In this case there is no reason to throw an error, but has prevented the execute function already in the code caller, not in the function body.

Upvotes: 0

topshot
topshot

Reputation: 885

You would use an Exit Sub call to stop executing that routine right there. If it had been a function, Exit Function

BTW, you should use CInt rather than Val to force to integer and your message should be more helpful (i.e., what was the error while computing?). Something along the lines of "First integer must be less than the second" would be more useful to a user.

Upvotes: 2

Haytam
Haytam

Reputation: 4733

Try one of these to exit a method

Exit Sub

Or

Return

Simple use :

Dim intm As Integer, intn As Integer
Dim intmod As Integer
intm = Val(TextBox1.Text)
intn = Val(TextBox2.Text)

If TextBox1.Text >= TextBox2.Text Then
    MsgBox("Error while computing proccess ! Please try Again.", vbOKOnly + vbCritical, "Error!")
    Exit Sub
End If

intmod = remainder(intm, intn)
RichTextBox1.Text = "The result is " & Str(intmod) 

Upvotes: 1

Related Questions