Exception Handling in VB.Net

Discussion in 'Visual Basic [VB]' started by pradeep, Apr 8, 2007.

  1. pradeep

    pradeep Team Leader

    Apr 4, 2005
    Likes Received:
    Trophy Points:
    Kolkata, India
    Home Page:
    One of the most reputable changes in the Visual Basic language is the introduction of structured exception handling in VB.NET. While the latest version of the language still supports the On Error Goto type of error handling, it's not preferred; instead, you should use structured exception handling.

    VB.NET now supports the Try Catch exception blocks and Try Finally resource protection blocks. Here is more information about both types of structured exception handling blocks, along with code samples.

    Try ... Catch

    The Try Catch block allows you to catch and handle errors for which the developer can specify a resolution. The basic format of the block is:

      'Some code
      'Error resolution whenever an error takes place
     End Catch
    The protected code appears in the Try section of the code, and the error resolution appears in the Catch section of the code. The Try code always gets executed, but the Catch code only gets executed if an error occurs.

    Try ... Finally

    The Try Finally blocks are usually used in order to ensure that allocated resources are being cleaned up. These blocks allow you to catch and handle errors, as well as execute a section of the code regardless of whether there is an error. The basic format of the block is listed below:

    'Resource allocation code
      'Use the resource
      'Clean the resource up
     End Catch
    The protected code appears in the Try section, and the clean up code appears in the Finally section. The statements in a Finally block are always executed when control leaves a try statement, regardless of whether there is an error in the execution.

    Note: In real applications, you will often need to combine or nest the Try Catch and Try Finally blocks to design a more flexible error handling routine.
  2. Steel9561

    Steel9561 New Member

    Apr 26, 2008
    Likes Received:
    Trophy Points:
    I have always wondered if VB .NET copied this from Java as I am very familiar that Java uses Try catch statements in the same way. What do you all think?

    Luis Lazo
    Last edited by a moderator: May 1, 2008

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice