Try-Catch problems

darkhunterd

New member
Joined
Feb 23, 2008
Messages
3
Programming Experience
Beginner
Hello, i'm kinda a newbie in a lot of things related to vb. I can't seem to find the error regarding one function that i made that uses a try-catch code but it really doesn't do anything.

read in the book so this is the last modification
http://www.nomorepasting.com/getpaste.php?pasteid=12033

my first one was like this
http://www.nomorepasting.com/getpaste.php?pasteid=12034

neither perform try-catch as supposed.

Please help i really want to know what i'm doing wrong :eek:.

thanks for your help :)

P.S. sorry if i posted on the wrong section
 
hi

i i understood your problem well - you need to trap the division by zero?

I teted out as follows and it worked:

VB.NET:
    Private Function decimalsum(ByVal den1 As Decimal, ByVal den2 As Decimal, ByVal num1 As Decimal, ByVal num2 As Decimal) As Double
        Dim partialResult1, partialResult2, decimalresult As Double

        Try
            partialResult1 = num1 / den1
        Catch Exception As DivideByZeroException
            MessageBox.Show("Trato de dividir por cero")
        End Try

        Try
            partialResult2 = num2 / den2
        Catch Exception As DivideByZeroException
            MessageBox.Show("Trato de dividir por cero")
        End Try

        decimalresult = partialResult1 + partialResult2

        Return decimalresult
    End Function

and to test the code:

VB.NET:
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim result = decimalsum(0, 0, 1, 1)
    End Sub

The message box was shown

HTH
 
hmmm

well i just included "ByVal den1 As Decimal," - the As Decimal...

you can always create another catch statement that will handle ALL errors

example:

VB.NET:
        Try
            partialResult1 = num1 / den1
        Catch Exception As DivideByZeroException
            MessageBox.Show("Trato de dividir por cero")
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try

        Try
            partialResult2 = num2 / den2
        Catch Exception As DivideByZeroException
            MessageBox.Show("Trato de dividir por cero")
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
 
Your function doesn't return a correct result if den1/den2 is 0, so you should throw ArgumentException if this is the case.
VB.NET:
Private Function decimalsum(ByVal den1 As Double, ByVal den2 As Double, ByVal num1 As Double, ByVal num2 As Double) As Double
    If den1 = 0 OrElse den2 = 0 Then
        Throw New ArgumentException("den1/den2 parameters values cannot be 0.")
    End If
    Return (num1 / den1) + (num2 / den2)
End Function
VB.NET:
Try
    Dim d As Double = decimalsum(0, 1, 1, 1)
Catch ex As Exception
    MsgBox(ex.Message)
End Try
 
Back
Top