Type of Errors
In .NET, there are primarily three types of errors:
Compilation Errors
Compilation errors occur during the compilation
phase of the code, indicating that the code
violates the rules of the programming language
or contains syntax errors.
These errors prevent the code from being
successfully compiled into an executable or
assembly.
Common compilation errors include missing or
misplaced parentheses, semicolons, or incorrect
variable declarations.
Compilation errors must be fixed before the
code can be executed.
Logical Errors
Logical errors, also known as bugs, occur when
the program's logic or algorithm is incorrect,
resulting in unintended or incorrect behavior.
These errors do not cause the program to
crash or generate exceptions, but they lead to
incorrect outputs or unexpected results.
Logical errors can be challenging to identify and
fix since they require careful examination of
the code's logic and understanding of the
expected behavior.
Debugging techniques like stepping through the
code, inspecting variables, and using logging can
help in identifying and resolving logical errors.
Runtime Errors
Runtime errors, also known as exceptions, occur
during the execution of a program. They are
typically caused by unexpected or exceptional
conditions that the program encounters during
runtime.
These errors can be due to various factors such
as invalid input, division by zero, accessing null
objects, or attempting to perform an operation
that is not supported.
When a runtime error occurs and is not properly
handled, it can lead to program termination or
undesired behavior.
To handle runtime errors, exception handling
mechanisms are used, such as try-catch blocks,
to recover from exceptional conditions and
prevent the application from crashing.
VB.Net - Exception Handling
An exception is a problem that arises during
the execution of a program. An exception is a
response to an exceptional circumstance that
arises while a program is running, such as an
attempt to divide by zero.
Exceptions provide a way to transfer control
from one part of a program to another. VB .Net
exception handling is built upon four keywords –
Try, Catch, Finally and Throw.
Try, Catch, Finally and Throw
Try − A Try block identifies a block of code for
which particular exceptions will be activated. It's
followed by one or more Catch blocks.
Catch − A program catches an exception with an
exception handler at the place in a program where
you want to handle the problem. The Catch keyword
indicates the catching of an exception.
Finally − The Finally block is used to execute a
given set of statements, whether an exception is
thrown or not thrown. For example, if you open a
file, it must be closed whether an exception is
raised or not.
Throw − A program throws an exception when a
problem shows up. This is done using a Throw keyword.
Exception Classes in .Net Framework
In the .Net Framework, exceptions are
represented by classes. The exception classes in
.Net Framework are mainly directly or indirectly
derived from the System.Exception class. Some
of the exception classes derived from the
System.Exception class are the
System.ApplicationException andSystem.System
Exception classes.
The System.ApplicationException class supports
exceptions generated by application programs. So
the exceptions defined by the programmers
should derive from this class.
The System.SystemException class is the base
class for all predefined system exception.
The following diagram will illustrate more details about
the exception classes in visual basic.
Module Module1
Sub Main(ByVal args As String())
Dim name As String = Nothing
' Null Reference Exception Error
If name.Length > 0 Then
Console.WriteLine("Name: " & name)
End If
End Sub
End Module
Handling Exceptions
VB.Net provides a structured solution to the
exception handling problems in the form of try
and catch blocks. Using these blocks the core
program statements are separated from the
error handling statements.
These error handling blocks are implemented
using the Try, Catch and Finally keywords.
Following is an example of throwing an
exception when dividing by zero condition
occurs:
Module Program
Sub division(ByVal num1 As Integer, ByVal num2
As Integer)
Dim result As Integer
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
Public Class Temperature
Dim temperature As Integer = 0
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.
We can use a throw statement in the catch block to
throw the present object as:
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)
In visual basic, Property is an extension of the class
variable and it provides a mechanism to read, write or
change the value of the class variable without affecting
the external way of accessing it in our applications.
In visual basic, properties can contain one or two code
blocks called accessors and those are called a Get
accessor and Set accessor. By using Get and Set
accessors, we can change the internal implementation of
class variables and expose it without effecting the
external way of accessing it based on our requirements.
Generally, in object-oriented programming languages like
visual basic we need to define fields as Private, and use
the properties to access their values in Public way with
Get and Set accessors.
Following is the syntax of defining a property with Get
and Set accessor using Property keyword in a visual basic
programming language.
<access_modifier> Property <property_name> As <return_type>
{
Get
// return property value
End Get
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.
Here, the Get accessor code block will be executed whenever
the property is read and the code block of Set accessor will be
executed whenever the property is assigned to a new value.
Types of Properties in VB .NET
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.
Read-Only A property which contains
only Get accessor with ReadOnly property,
we will call it as a read-only property.
Write-Only A property which contains
only Set accessor
with WriteOnly property, we will call it as
write-only property.
Following is the simple example of defining the private variable and
property in a visual basic programming language.
Class Student
Private name As String
Public Property Sname As String
Get
Return name
End Get
Set(ByVal value As String)
name = value
End Set
End Property
End Class
If you observe the above example, we defined a property called “Sname”
and we used Get accessor to return the property value and Set accessors
to set the new value. Here, the value keyword in Set accessor is used to
define the value that is being assigned by Set accessor.
As discussed, we can extend the behavior of class
variables using properties Get and Set accessors.
Following is the example of extending the behavior of
Private variable in property using Get and Set accessors in
a visual basic programming language.
Class User
Private name As String = “Allan Simpsion"
Public Property Uname As String
Get
Return name.ToUpper()
End Get
Set(ByVal value As String)
If value = “Allan" Then name = value
End Set
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.
Here the field “name” is marked as Private. So, if you want to
make any changes to this field, you can do it only by calling
the property (UName).
In visual basic properties, the Get accessor will be invoked
while reading the value of property and when we assign a new
value to the property, then the Set accessor will be invoked
by using an argument that provides a new value.
Following is the example of invoking the Get and Set
accessors of properties in a visual basic programming
language.
Dim u As User = New User()
u.Uname = “Peter" ' Set accessor will invoke
Console.WriteLine(u.Uname) ' Get accessor will invoke
Visual Basic Properties (Get, Set) Example
Following is the example of defining the properties with Property
keyword, Get and Set accessors to implement required validations
without effecting the external way of using it in visual basic
programming language.
Module Module1
Class User
Private location As String
Private name As String = “Allan Simpsion"
Public Property Ulocation As String
Get
Return location
End Get
Set(ByVal value As String)
location = value
End Set
End Property
Public Property Uname As String
Get
Return name.ToUpper()
End Get
Set(ByVal value As String)
If value = “Allan" Then name = value
End Set
End Property
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
If you observe the above example, we are extending the
behaviour of private variables (name, location) using properties
(Uname, Ulocation) with Property keyword, Get and Set
accessors by performing the some validations like to make sure
Uname value is equals to only “Allan” using Set accessor and
converting property text to uppercase with Get accessor.
Visual Basic Create Read-Only Properties
As discussed, if property contains only Get accessor
with ReadOnly property, we will call it as read-only
property.
Following is the example of creating read-only
properties in a visual basic programming language.
Module Module1
Class User
Private name As String
Private location As String
Public Sub New(ByVal a As String, ByVal b As String)
name = a
location = b
End Sub
Public ReadOnly Property Uname As String
Get
Return name
End Get
End Property
Public ReadOnly Property Ulocation As String
Get
Return location
End Get
End Property
End Class
Sub Main()
Dim u As User = New User(“Allan Simpsion", “New York")
' Compile-time error
' u.Name = “Peter";
' Get accessor will invoke
Console.WriteLine("Name: " & u.Uname)
' Get accessor will invoke
Console.WriteLine("Location: " & u.Ulocation)
Console.WriteLine("Press Enter Key to Exit..")
Console.ReadLine()
End Sub
End Module
Visual Basic Create Write Only Properties
As discussed, if property contains the only Set
accessor with WriteOnly property, we will call it as
write-only property.
Following is the example of creating write-only
properties in a visual basic programming language.
Module Module1
Class User
Private name As String
Public WriteOnly Property Uname As String
Set(ByVal value As String)
name = value
End Set
End Property
Private location As String
Public WriteOnly Property Ulocation As String
Set(ByVal value As String)
location = value
End Set
End Property
Public Sub GetUserDetails()
Console.WriteLine("Name: " & name)
Console.WriteLine("Location: " & location)
End Sub
End Class
Sub Main()
Dim u As User = New User()
u.Uname = “Allen Simpsion"
u.Ulocation = “New York"
' Compile-time error
'Console.WriteLine(u.Uname);
u.GetUserDetails()
Console.WriteLine("Press Enter Key to Exit..")
Console.ReadLine()
End Sub
End Module
Visual Basic Auto Implemented Properties
In visual basic, a property is called as an auto-
implemented property when creating it with only
Property keyword.
Generally, the auto-implemented properties are useful
whenever there is no logic implementation required in
property accessors.
Following is the example of creating the auto-
implemented properties using Property keyword in a
visual basic programming language.
Module Module1
Class User
Public Property Name As String
Public Property Location As String
End Class
Sub Main()
Dim u As User = New User()
u.Name = “Allan Simpsion"
u.Location = “New York"
Console.WriteLine("Name: " & u.Name)
Console.WriteLine("Location: " & u.Location)
Console.WriteLine("Press Enter Key to Exit..")
Console.ReadLine()
End Sub
End Module
If you observe the above example, we created auto-implemented
properties using only Property keyword without having any logic
implementation.
Visual Basic Properties Overview
The following are the important points which we need
to remember about properties in a visual basic
programming language.
In visual basic, properties will enable the class
variables to expose in public way using Get and Set
accessors with Property keyword by hiding
implementation details.
In properties, the Get accessor is useful to return
the property value and the Set accessor is useful to
assign a new value.
The value keyword in Set accessor is useful to
define the value which is going to be assigned by the
Set accessor.
In visual basic, properties are categorized as read-
write, read-only or write-only.