VB. NET Exception Handling and throwing exceptions

Source: Internet
Author: User
Tags finally block

Exception Handling is. an important security mechanism of the. NET platform, which perfectly separates the acceptance and handling of error codes, clarifies the programmer's thoughts, and enhances the readability of the Code, it facilitates the maintainer's reading and understanding, and provides methods to handle any unexpected or abnormal situations when the program is running. On the. NET platform, you can use the try, catch, and finally keywords for exception handling to try operations that may fail, handle failures, and clear resources afterwards. Exception Handling (also known as error handling. Compared with the on error statement in traditional VB6.0, the exception handling mechanism on the. NET platform is more flexible and convenient to use.


I. Three statement blocks for Exception Handling

. In the. NET platform, exception handling mainly consists of try/catch/finally statement blocks. Try blocks are responsible for capturing error codes and catch for error handling, finally is responsible for subsequent work after error handling, such as releasing objects and clearing resources.

Try 'program code catch 'to handle Exception Code finally 'clean up work end try

In the preceding statement blocks, try and finally statement blocks must be run, but catch statement blocks may not be run. If the code in try blocks is correct and no exception is thrown, the code in the Catch Block does not run. Instead, it skips the Catch Block and directly runs the cleanup work in the Finally block. If an exception Catch Block is encountered, the processing is required.

Why is it necessary to clean up the Finally block? Simply put, a program exception will cause the program to fail to complete the work normally, and jump out of the program where the error occurs, and directly execute the code in the catch statement block, this prevents the object Resources built during the program running from being released, wastes memory resources, and may also lead to messy data storage in the stack, therefore, no matter whether an exception occurs, the code in the Finally block will certainly run.

Code example for exception handling:

Private Sub FirstTryCatchButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FirstTryCatchButton.Click        Dim sngAvg As Single        sngAvg = GetAverage(0, 100)End SubPrivate Function GetAverage(ByVal iItems As Integer, ByVal iTotal As Integer) As Single        ' Code that might throw an exception is wrapped in a Try block        Try            Dim sngAverage As Single            ' This will cause an exception to be thrown if iItems = 0            sngAverage = CSng(iTotal \ iItems)            ' This only executes if the line above generated no error            MessageBox.Show("Calculation successful")            Return sngAverage        Catch excGeneric As Exception            ' If the calculation failed, you get here            MessageBox.Show("Calculation unsuccessful - exception caught")            Return 0        End TryEnd Function
Ii. Throw an exception

We know that exceptions in the program will cause the program to jump out of the program in advance, and also throw exceptions to jump out of the program code and directly run the content in the Catch Block. Throwing an exception not only can cause an error in the program code, but we can also use the throwing exception mechanism to capture abnormal values in a process or function, you can think of this method as a function that returns a special value and uses upper-layer functions to capture exceptions in the program. VB. NET uses the throw keyword to throw an exception in the program, so that the upper-level calling function that calls this function can handle the exception.

Private Sub ThrowNewExceptionButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ThrowNewExceptionButton.Click        Try            Dim sngAvg As Single            sngAvg = GetAverage4(0, 100)        Catch exc As Exception            MessageBox.Show(exc.Message)        Finally            MessageBox.Show("Finally block in click event")        End TryEnd SubPrivate Function GetAverage4(ByVal iItems As Integer, ByVal iTotal As Integer) As Single        If iItems = 0 Then            Dim excOurOwnException As New ArgumentException("Number of items cannot be zero")            Throw excOurOwnException        End IfEnd Function

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.