Vb. NET edition room charge system---exception handling

Source: Internet
Author: User
Tags finally block try catch

Exception handling, English name is exceptional handling, when young, still remember that year together studied VB6.0, often use onerror Error statement. The exception handling mechanism of the. NET platform is more flexible and easier to use than the onerror statements in traditional VB6.0. is a new law that replaces the fading error code method, providing an advantage that error code has not been able to specify. Exception handling cleverly and flawlessly separates the receive and process error codes. This function makes the programmer's mind clear, and it also helps the code to improve readability and facilitates reading and understanding of the maintainer.

Exception handling, also known as error handling, provides a way to handle any unexpected or unusual conditions that occur when a handler runs. Exception handling uses the try, catch, and finally keywords to try operations that might not succeed, handle failures, and clean up resources afterwards. Exception handling is usually the action taken to prevent an unknown error from arising. The advantage of exception handling is that you don't have to work your brains out to think about all kinds of errors, which provides a very effective way to deal with a certain kind of error, which greatly improves the efficiency of programming.

One, exception handling try ... Catch... Finally

<span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:18PX;" >    Try          ' program code       Catch         ' handles exception code      Finally          ' cleanup work      End try</span></span>
In the above statement, the TRY statement block usually holds the code that we need to detect a possible exception, that is, if the program is correct, execute a try statement block, and the catch statement block is responsible for catching the wrong code. So when this code produces an exception during execution, it goes to the catch block and handles the exception accordingly. Finally, the code in the finally block is bound to be executed, regardless of whether an exception is thrown. The finaly block is used to clear any resources allocated in a try block and to run any code that must be executed even when an exception occurs. Catch and finally statements can be used together in a try block.

Simply put, the try and finally statement blocks must be run, but the catch statement does not necessarily run, and if the code inside the try block does not have an error and throws an exception, the code in the Catch statement block is not running. Instead, the catch block is skipped to run cleanup work directly in the finally block. Conversely, if you encounter an exception, the processing in the block of catch statements is going to take place. Why clean up in a finally block? Simply say that a program's exception will cause the program not to complete the work, and in the wrong place to jump out of the program, directly execute the code in the catch statement block, so that the object resources built at the time of the program run can not be freed, waste memory resources, but also may lead to the stack of data storage clutter, So the code in the finally block is bound to run, whether or not an exception occurs.
For example, how do we apply exception handling in the code with the registration of the vb.net version of the computer room charging system?

<span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:18PX;" > Private Sub btnsave_click (sender as Object, e as EventArgs) Handles Btnsave.click Try Dim registerm Anager as New BLL.            Registermanager Dim studentinfo As New Entity.studentinfo Dim cardinfo As New Entity.cardinfo Dim Rechargeinfo as New entity.rechargeinfo If (Registermanager.query (Txtstudentno.text) is nothing and regist Ermanager.querycard (Txtcardno.text) is nothing) then Studentinfo.cardno = Txtcardno.text Stu Dentinfo.studentno = Txtstudentno.text Studentinfo.studentname = txtName.Text studentinfo.se x = Cmbsex.text Studentinfo.department = Txtdepartment.text Studentinfo.grade = Txtgrade.tex T Studentinfo.stuclass = txtclass.text Studentinfo.remark = Txtremark.text St Udentinfo.                Handler = FrmLogin.handler.handler' User display layer does not have the processing person this text box, how to do?                The database inside handler This field information how to obtain, the answer is above oh. Cardinfo.cardno = Txtcardno.text cardinfo.balance = txtbalance.                Text cardinfo.status = "use" Cardinfo.registerdate = CStr (Format (now (), "YYYY-MM-DD")) Cardinfo.registertime = CStr (Format (now (), "HH:mm:ss")) Cardinfo.handler = FrmLogin.handler.handle R Cardinfo.ischeck = "Not checkout" Rechargeinfo.cardno = Txtcardno.text rechargeinfo. Rechargeamount = txtbalance. Text rechargeinfo.rechargedate = CStr (Format (now (), "Yyyy-mm-dd")) Rechargeinfo.time = CStr ( Format (now (), "HH:mm:ss")) Rechargeinfo.userid = FrmLogin.handler.handler registermanager.in SERT (Studentinfo) Registermanager.insertcard (cardinfo) Registermanager.insertrecharge (Rechar       Geinfo) MsgBox ("User registration successful") End If Catch ex as Exception     MessageBox.Show (ex. Message.tostring ()) End Try End sub</span></span>
If we do not write this statement that catches the exception, the registration fails in the D layer, what will the result be?

As shown, she jumps directly to the wrong place, but what happens if you write a try Catch in the program?

Two different ways of error, the second kind of feeling more intuitive, help us to clear up the mind, enhance the readability of the Code, to facilitate the maintenance of reading and understanding.

Second, throw an exception

When a program is in an abnormal condition, it causes the system to jump out of the program in advance, catching the exception with catch, allowing us to proceed with the catch. Try...catch captures the error that the system detects itself. We can use the Throw keyword to throw an exception in the program if we need to customize some errors, such as when a card number does not exist.
The throw keyword is typically used in the method body and throws an exception object, and if a method does not catch an exception that might be thrown, other methods that call the method should catch and handle the exception. The program terminates immediately when it executes to the throw statement, and the statements following it are not executed. After throwing an exception through throw, if you want to catch and handle the exception in the previous level of code, you need to use the throws keyword in the method that throws the exception to indicate the exception to throw in the declaration of the method, and if you want to catch the exception thrown by the throw, you must use the Try-catch statement. For example, in order to ensure that the logic is correct, in the program to judge if the logic of the part can throw an exception, such as: No number is not except 0, if 0 as a divisor will throw an exception, throw new Exception ("0 cannot be a divisor!") ")

The code is as follows:

<span style= "FONT-SIZE:18PX;" >private Sub Butntest_click (sender as Object, e as EventArgs) Handles Button1.Click            Try              Dim g as Integer =3
   
    dim h as Integer =0              TextBox1.Text = Gettry (g, h)            Catch ex as Exception              MsgBox ("divisor cannot be 0", vbOKOnly + Vbinformat Ion, "system Message")            Finally              MsgBox ("End")            end Try            end Sub    Private Function gettry (ByVal A as Integer, B as I Nteger) as Integer            If b = 0 Then              Dim excourownexception as New ArgumentException ("divisor cannot be 0")      ' throws an exception              Throw excourownexception          End If    end Function  </span>
   
with exception handling, most of the normal code can be separated from a few exception handling, followed by error classification, and finally notify the user of the specific error. Computer room charge system, not finished, to be continued ...

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.