Exception Handling in VB .Net

Introduction of Exception Handling in VB .net

  • Exception:

    • An Exception, in OOP programming, is a hidden, unwanted, abnormal, unexpected, or exceptional event that occurs during the execution of a program and interrupts the normal flow of the program.
    • When a program encounters an exception, it stops executing the current code block and immediately transfers control to a special piece of code called an exception handler. The exception handler typically handles the exception by providing an appropriate response, such as displaying an error message or logging the error for further analysis.
    • An Exception may be a System exception or an Application exception.
    • Exceptions can occur for a variety of reasons, such as invalid input data, unexpected program behavior, or resource limitations.
    • By using exceptions, programmers can write more robust and fault-tolerant code that can handle unexpected situations and recover from errors.
  • Exception handling is a critical concern of OOPs programming languages, including VB .NET.
  • VB .NET provides a robust set of features for handling exceptions, which helps the developer write more reliable and efficient code.

Definition of Exception Handling in VB .net

  • In VB .NET, exception handling is a programming mechanism that enables programmers to handle run-time sudden errors and other exceptional conditions.
  • Exception handling is an OOP programming concept that refers to the process of identifying, catching, and responding to errors or exceptional events that occur during the execution of a program.

Features of Exception Handling in VB .net

  • The purpose of exception handling in VB .NET is to provide a structured and reliable way to handle errors, prevent crashes, and recover from unexpected situations that may arise during program execution.
  • By handling exceptions, developers can provide a better user experience, improve application stability, and help prevent data loss or corruption. In other words, the goal of exception handling is to improve the reliability and robustness of software applications by providing a mechanism to gracefully recover from errors and unexpected events.
  • Additionally, VB .NET also provides several other error-handling constructs, such as the On Error statement and the Throw statement, which can be used in conjunction with the Try-Catch-Finally block to provide more advanced error-handling capabilities.

Structure of Exception Handling in VB .net

  • When an exceptional event, such as an error, occurs in a program, an exception is thrown, and the program can choose to handle the exception in a way that prevents the program from crashing or producing incorrect results.
  • In VB .NET, exceptions are objects that are created when a run-time error occurs, and they contain information/messages about the error, such as its type and message.
  • In VB .Net, exception handling may be performed using four structured error-handling constructs /built-in keywords: Try, Catch, Finally, and Throw.

Try 

    • The Try block is compulsory.
    • The Try block is the region of the program where the main code is written, and this code may throw an exception, if any. 

Catch

    • The Catch block is compulsory.
    • This block accepts the exception information thrown by the Try block.
    • The Catch block contains the code that is executed when an exception is caught.

Finally

    • The Finally block is optional and is used to specify code that should always be executed, regardless of whether an exception occurred or not.
  • Exception Classes  in VB .Net :
    • In VB .Net, all the exception classes originate from the parent class System. Exception‘.
    • In VB .Net, there are two main exception classes used primarily to handle various types of exceptions. 
      1. System.SystemException
      2. System.ApplicationException

      System.SystemException: (Pre-defined/In-Built Exception) This exception class includes all predefined and some system-generated exception classes that arise during the run time. For example – DivideByZeroException, IndexOutOfRangeException, StackOverflowException, and so on.

      System.ApplicationException: (User-defined Exception) This exception class throws an exception defined within the application by the programmer or developer. This exception was created by inheriting from System.ApplicationException class.

Syntax of Exception Handling in VB .net

  • The general form of Syntax is

Try
       ‘ Programmer Codes that may throw an exception
Catch ex As Exception
       ‘ Codes to handle the exception
Finally
       ‘ Code that should always be executed
End Try

OR

Try  

     Codes or Statements   

    [ Exit Try ]     ‘If necessary

Catch [ Exception name] As [ Exception Type]   

    [Catch Statements] Catch [Exception name] As [Exception Type]  

    [ Exit Try ]     ‘If necessary

 Finally  

    [ Finally Statements ]   

End Try  

  • In VB.NET, we can create a customized Catch statement to handle specific exceptions based on their type, message, or other criteria. We can use the ‘When’ keyword to specify a condition that must be met for the Catch block to execute. For example – 

Try
     ‘ Main codes that might throw an exception.
Catch ex As Exception when ex.Message.Contains(“Invalid”)
    ‘ Codes to handle exceptions with “Invalid” in the error message.
Catch ex As Exception When TypeOf ex Is FileNotFoundException
    ‘ Codes to handle FileNotFoundExceptions.
Finally
    ‘ Codes that always execute, regardless of whether an exception was thrown.
End Try

  • We can also include multiple Catch blocks to handle different types of exceptions. For example:-

Try
     ‘ Main codes that might throw an exception
Catch ex As FileNotFoundException
     ‘ Codes to handle the specific “file not found” exception

Catch ex As IOException
     ‘ Codes to handle IOExceptions 

Catch ex As ArgumentException
     ‘ Codes to handle ArgumentExceptions 
Catch ex As Exception
     ‘ Codes to handle all other/general exceptions
End Try

  • We can also use the Throw statement to manually throw an exception. This can be useful for testing exception handling code or for creating custom exceptions. For example:-

Throw New ApplicationException(“A customized error message occurred!”)

  • Nested Try/Catch Blocks Statement: The nested try/catch blocks are used to handle exceptions at different levels of code execution.

Try
      ‘ some code that might throw an exception
      Try
              ‘ some nested code that might throw a different exception
      Catch ex As Exception
              ‘ handle nested exception here
      End Try
Catch ex As Exception
      ‘ handle all other exceptions here
End Try

NB: If an exception occurs that doesn’t match any of the specified types, it will be caught by the final/last catch block. 

Example of Exception Handling in VB .net

Try
    Dim a As Integer = 10
    Dim b As Integer = 0
    Dim c As Integer = a / b
Catch ex As Exception
    MessageBox.Show(“Error: ” & ex.Message)
Finally
    MessageBox.Show(“Operation Completed”)
End Try

Working Mechanism of Exception Handling in VB .net

The overview of how exception handling works in VB .NET is :-

  • The Try block contains the major code of the program that may cause an exception to be thrown. When an error occurs during the execution of a block of code, VB .NET throws an exception.
  • The exception is an object that contains information about the error, such as its type and message.
  • Now the thrown exception is caught and handled gracefully using the Catch block/statement, i.e., the Catch block is executed when an exception is thrown. It contains the code that handles the exception.
  • The finally block is executed regardless of whether an exception is thrown or not. It contains the code that must be executed, regardless of whether an exception occurs.

Common Exception Types in Windows Forms

  • DivideByZeroException
  • FormatException
  • NullReferenceException
  • OverflowException
  • IOException

Error Handling in VB .Net

  • Error handling in Windows Forms applications is used to detect, prevent, and handle errors gracefully so that the application does not crash and provides proper feedback to the user.
  • Error handling in Windows Forms ensures that invalid input and runtime errors are properly detected and handled without crashing the application.
  • VB .NET provides tools like Try–Catch, ErrorProvider, and MessageBox for effective error handling.
  • Validation is the process of checking user input before processing it.
  • Types of Validations in Windows Forms
    • Required Field Validation
      • This validation ensures that the user does not leave mandatory fields empty.
      • Example:
Checking whether a TextBox is empty before submission.

If TextBox1.Text = “” Then
    MessageBox.Show(“Field cannot be empty”)
End If
    • Data Type Validation
      • This validation ensures that the input is of the correct data type, such as numeric, string, or date.
      • Example:
If Not IsNumeric(TextBox1.Text) Then
    MessageBox.Show(“Enter a numeric value”)
End If
    • Range Validation
      • This validation ensures that the input value lies within a specified range.
      • Example:
Dim age As Integer = Val(TextBox1.Text)
If age < 1 Or age > 100 Then
    MessageBox.Show(“Age must be between 1 and 100”)
End If
    • Length Validation
      • This validation checks the minimum or maximum length of input.
      • Example: 
If TextBox1.Text.Length < 6 Then
    MessageBox.Show(“Minimum 6 characters required”)
End If
    • Format Validation
      • This validation ensures that the input follows a specific format, such as an email or phone number.
      • Example:
If Not TextBox1.Text.Contains(“@”) Then
    MessageBox.Show(“Invalid email format”)
End If
    • Control-Based Validation
      • Windows Forms provides controls like ErrorProvider to display validation errors near the control.
  • Types of Errors in VB .NET
    • Errors are problems that occur during program development or execution. These are –
    • Syntax Errors
      • Syntax errors occur when the program violates the rules of the VB .NET language.
      • These errors are detected at compile time.
      • Example: Missing End If statement.
    • Runtime Errors
      • Runtime errors occur while the program is running and may cause the program to crash if not handled.
      • Example: Dividing a number by zero.
Dim x As Integer = 10
Dim y As Integer = 0
Dim z As Integer = x / y   ‘ Runtime error
    • Logical Errors
      • Logical errors occur when the program runs successfully but produces incorrect output.
      • Example: Using + instead of * in a calculation.

Loading


0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.