Write a Vb.net program to add two TextBoxes, two Labels and one button at runtime. Accept two numbers in textboxes and handle DivideByZeroException.

 Program:-

Public Class slip6

    Dim t1 As New TextBox

    Dim t2 As New TextBox

    Dim l1 As New Label

    Dim l2 As New Label

    Dim b1 As New Button

    Dim n As Integer

    Private Sub slip6_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        l1.Top = 100

        l1.Left = 100

        l1.Text = "Enter 1st Number"

        l1.Visible = True

        Me.Controls.Add(l1)


        l2.Text = "Enter 2nd Number"

        l2.Top = 100

        l2.Left = 300

        l2.Visible = True

        Me.Controls.Add(l2)


        t1.Top = 125

        t1.Left = 100

        t1.Visible = True

        Me.Controls.Add(t1)


        t2.Top = 125

        t2.Left = 300

        t2.Visible = True

        Me.Controls.Add(t2)


        b1.Text = "Divide"

        b1.Top = 190

        b1.Left = 220

        b1.Visible = True

        Me.Controls.Add(b1)

        AddHandler b1.Click, AddressOf b1_Click

    End Sub


    Private Sub b1_Click()

        Try

            n = CInt(t1.Text) \ CInt(t2.Text)

            MsgBox(n)

        Catch ex As DivideByZeroException

            MsgBox(ex.Message)

        End Try

    End Sub

End Class


Output:-



Theory:-

A try-catch statement consists of a try block followed by one or more catch clauses, which may handle various exceptions. when try block throws an exception,Visual basic looks for the catch statement that handles the exception.

DivideByZeroException is used to handles the exception if any number divide by zero.

Note - Set startup form's application type as Windows Form Application


0 Comments