TypesOfError ExceptionHandling
TypesOfError ExceptionHandling
Compilation Errors
Try
result = num1 \ num2
Catch e As DivideByZeroException
Console.WriteLine("Exception caught: {0}", e)
Finally
Console.WriteLine("Result: {0}", result)
End Try
End Sub
Sub Main(args As String())
division(25, 0)
Console.ReadKey()
End Sub
End Module
Creating User-Defined Exceptions
You can also define your own exception. User-
defined exception classes are derived from the
ApplicationException class. The following
example demonstrates this:
Module exceptionProg
Public Class TempIsZeroException : Inherits ApplicationException
Public Sub New(ByVal message As String)
MyBase.New(message)
End Sub
End Class
Sub showTemp()
If (temperature = 0) Then
Throw (New TempIsZeroException("Zero Temperature found"))
Else
Console.WriteLine("Temperature: {0}", temperature)
End If
End Sub
End Class
Sub Main()
Dim temp As Temperature = New Temperature()
Try
temp.showTemp()
Catch e As TempIsZeroException
finally
Console.WriteLine("TempIsZeroException: {0}", e.Message)
End Try
Console.ReadKey()
End Sub
Throwing Objects
We can throw an object if it is either directly or
indirectly derived from the System.Exception class.
Module exceptionProg
Sub Main()
Try
Throw New ApplicationException("A custom exception
_is being thrown here...")
Catch e As Exception
Console.WriteLine(e.Message)
Finally
Console.WriteLine("Now inside the Finally Block")
End Try
Console.ReadKey()
End Sub
End Module
Visual Basic Properties (GET, SET)
Set
// Set a new value
End Set
}
If you observe the above syntax, we used an access modifier,
Property keyword, and return type to define a property along
with Get and Set accessors to make the required modifications
to the class variables based on our requirements.
Type Description
Read-Write A property which contains a
both Get and Set accessors
with Property keyword, we will call it as
read-write property.
Class Student
Get
Return name
End Get
name = value
End Set
End Property
End Class
Class User
Get
Return name.ToUpper()
End Get
End Property
End Class
If you observe above example, we are extending the behavior
of Private variable name using property called Uname with
Get and Set accessors by performing some validations like to
make sure Uname value is equals to “Allan” using Set accessor
and converting the property text to uppercase with Get
accessor.
Class User
Get
Return location
End Get
location = value
End Set
End Property
Public Property Uname As String
Get
Return name.ToUpper()
End Get
End Class
Sub Main()
Dim u As User = New User()
u.Uname = “Peter"
u.Ulocation = “New York"
Console.WriteLine("Name: " & u.Uname)
Console.WriteLine("Location: " & u.Ulocation)
Console.WriteLine("Press Enter Key to Exit..")
Console.ReadLine()
End Sub
End Module
Class User
End Class
Sub Main()
End Sub
End Module