Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

VB.Net - Exception handling


May 13, 2021 vb.net


Table of contents


An exception is a problem that occurs during program execution. An exception is a response to an exception that occurs while the program is running, such as an attempt to divide by zero.

Exceptions provide a way to transfer control from one part of the program to another. V b. Net exception handling is based on four keywords: Try, Catch, Finally, and Trow.

  • Try : A Try block identifies a block of code for which particular exceptions will be activated. I t's followed by one or more Catch blocks. T he Try block identifies the block of code that activates a particular exception. It is 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. T he Catch keyword indicates the catching of an exception. T he program catches exceptions and uses exception handlers where the program wants to handle problems. The Catch keyword indicates that the exception was caught.

  • Finally : The Finally block is used to execute a given set of statements, whether an exception is thrown or not thrown. F or example, if you open a file, it must be closed whether an exception is raised or not. F inally: The Final block is used to execute a given set of statements, whether thrown or not. For example, if you open a file, you must close it whether or not you throw an exception.

  • Throw : A program throws an exception when a problem shows up. T his is done using a Throw keyword. W hen something goes wrong, the program throws an exception. This is done using the Throw keyword.

Grammar

Assuming that the block throws an exception, the method uses a combination of try and Catch keywords to catch the exception. T ry/ Catch blocks are placed around code that might generate exceptions. T he code in the Try/Catch block is called protected code, and the syntax for using Try/Catch looks like this:

Try
    [ tryStatements ]
    [ Exit Try ]
[ Catch [ exception [ As type ] ] [ When expression ]
    [ catchStatements ]
    [ Exit Try ] ]
[ Catch ... ]
[ Finally
    [ finallyStatements ] ]
End Try

You can list multiple catch statements to catch different types of exceptions in case your try block throws multiple exceptions in different situations.


. The exception class in the Net framework

In the .Net framework, exceptions are represented by classes. Exception classes in the .Net Framework are derived primarily, directly or indirectly, from the System.Exception class. Some of the exception classes derived from the System.Exception class are System.ApplicationException and System.SystemException classes.

The System.ApplicationException class supports exceptions generated by applications. So programmer-defined exceptions should be derived from this class.

The System.SystemException class is the base class for all predefined system exceptions.

The following table provides some predefined exception classes derived from the System.SystemException class:

The exception class Describe
System.IO.IOException Handles I/O errors.
Handling I/O errors.
System.IndexOutOfRangeException Handles errors generated when a method refers to an array index out of range.
When the method is processed, it refers to an error that occurs when an array index is out of range.
System.ArrayTypeMismatchException

Handles errors generated when type is mismatched with the array type

Errors generated when the processing type does not match the array type.

System.NullReferenceException Handles errors generated from deferencing a null object.
Handles errors generated from undring empty objects.
System.DivideByZeroException Handles errors generated from dividing a dividend with zero.
Deal with errors caused by divided dividends by zero.
System.InvalidCastException Handles errors generated during typecasting.
Handle errors generated during type conversion.
For System.OutOfMemoryException Handles errors generated from insufficient free memory.
Handle errors from out-of-available memory.
System.StackOverflowException Handles errors generated from stack overflow.
Handle errors from stack overflows.


Handle exceptions

Vb. N et provides a structured solution to handle exception handling issues in the form of try and catch blocks. Using these blocks, the core program statement is separated from the error handling statement.

These error handling blocks are implemented using the Try, Catch, and Findy keywords. Here's an example of throwing an exception in a zero-divide condition:

Module exceptionProg
   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()
      division(25, 0)
      Console.ReadKey()
  End Sub
End Module


When the above code is compiled and executed, it produces the following results:

Exception caught: System.DivideByZeroException: Attempted to divide by zero. 
at ...
Result: 0


Create a user-defined exception

You can also define your own exceptions. T he user-defined exception class is derived from the ApplicationException class. T he 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
          Console.WriteLine("TempIsZeroException: {0}", e.Message)
      End Try
      Console.ReadKey()
   End Sub
End Module


When the above code is compiled and executed, it produces the following results:

TempIsZeroException: Zero Temperature found


Throw objects

If it is derived directly or indirectly from the System.Exception class, you can throw an object.

You can use the trow statement in the catch block to throw the current object:

Throw [ expression ]


The following procedure illustrates this:

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


When the above code is compiled and executed, it produces the following results:

A custom exception is being thrown here...
Now inside the Finally Block