Enumeration is a related set of constants. They are used when working with many constants of the same type. It's declared with the Enum keyword.
Example
| Imports System.Console Module Module1 Enum Seasons Summer = 1 Winter = 2 Spring = 3 Autumn = 4 End Enum Sub Main() Write("Summer is the" & Seasons.Summer & "season") End Sub End Module |
Output of above code is the image below. To use a constant from the enumeration it should be referred like this, Seasons.Winter and so on.
Constants
When we have certain values that we frequently use while programming, we should use Constants. A value declared as constant is of fixed value that cannot be changed once set. Constants should be declared as Public if we want it to be accessed by all parts of the application. In Visual Basic .NET we use the Const keyword to declare a constant. The following line of code declares a constant: Public Const Pi as Double=3.14159265
Exception Handling
Exceptions are runtime errors that occur when a program is running and causes the program to abort without execution. Such kind of situations can be handled using Exception Handling. By placing specific lines of code in the application we can handle most of the errors that we may encounter and we can enable the application to continue running. VB .NET supports two ways to handle exceptions, Unstructured exception Handling using the on error goto statement and Structured exception handling using Try....Catch.....Finally
Let's look at the new kind of exception handling introduced in VB .NET which is the Structured Exception Handling. VB .NET uses Try....Catch....Finally block type exception handling. The syntax looks like this:
Module Module1
Sub Main()
Try
-
-
Catch e as Exception
-
-
Finally
End Try
End Sub
End Module
Example
| Imports System.Console Module Module1 Sub Main() Dim a = 0, b = 1, c As Integer Try c = b / a 'the above line throws an exception WriteLine("C is " & c) Catch e As Exception WriteLine(e) 'catching the exception End Try End Sub End Module |
The output of the above code displays a message stating the exception. The reason for the exception is because any number divided by zero is infinity. When working with Structured exception handling you can have multiple Catch blocks to handle different types of exceptions differently. The code in the Finally block is optional. If there is a Finally block in the code then that code is executed last.
No comments:
Post a Comment