[The Path to commercial software development for graduates] C # Exception Handling

Source: Internet
Author: User
Recently, I began to contact students, college interns and graduates. I would like to talk about some suggestions for these students wandering in the workplace, hoping to help these beginners enter the software development industry, this allows graduates to enter the software development company more smoothly to start their career and make a perfect turn in their life.
---------------------------------------- Exception Handling Structure

To develop software, you must have sufficient awareness of risks. Recognizing that commercial software runs under Complicated Circumstances will inevitably lead to various risks and errors, which need to be handled. Ignoring risks and mistakes, it is dangerous to assume that everything is harmonious.

Actively handle errors

ProgramIn development, You can actively handle errors and passively handle errors. When you actively handle errors, you can write them.CodeThe most common and most effective method for checking before performing a function is to check whether the method parameters are correct at the beginning of the method body. Actively checks the program running speed, and the system is more stable, and the risk is eliminated in the bud, to avoid later errors, so it is the preferred risk processing method. [Yuan Yongfu copyright]

For example, the following code actively handles errors.

Public IntDiv (IntA,IntB)

{

//Check the parameter. If B is 0, an error with 0 division will inevitably occur. Handle the error in advance.

If(B = 0)

{

Return0;

}

ReturnA/B;

}

This Code actively checks whether the parameters are correct and stops errors as soon as possible.

Passive Exception Handling

The methods for actively handling errors may be missing,C #You can use the exception capture mechanism to passively handle errors.

Before explaining an exception, you must first talk about the concept of the call stack of the program. In fact, basically allProgramming LanguageAll have the function of calling the stack. For example, when the program is runningF1Method calledF2,F2At a certain moment, the method is called again.F3And the methodF3The method is called at a certain time.F4. Then there is"F1 | F2 | F3 | F4"Call Stack. As shown in, the code of the program is displayed as a method-based layered structure like an onion, and the lower the layer, the lower the code.

C #The exception is the information about the program module error. if an exception is thrown, the program notifies the system program of the error. This exception is global. It starts from the throw point and pushes up along the call stack layer by layer, the higher the impact, the greater the impact. If a layer of code on the call stack can actively capture and handle this exception, the exception disappears and the system can run normally, if no code can capture exceptions, the exception will be thrown all the time.. NetFramework layer.

For exampleF1,F2,F3,F4In the call stack, if the methodF4An internal exception is thrown. The exception is first thrown to the method.F3, IfF3If the exception is not handled, the exception is thrown again.F2, IfF2If no processing is available, it will be thrown again.F1, IfF1If not processed, it is directly thrown. NetThe framework system itself.

This is a bit like a petition. The farmers in the village feel that they are not satisfied with the village chief's petition. The village chief does not handle the petition in the county, the county does not handle the petition in the province, and the province does not handle the petition in the central Government, the central government always handles any petition in a simple and crude way.

However, it is not good to disturb the center in everything,. NetThe framework is. NetCentral application,. NetThe following program error dialog box is displayed when the framework handles exceptions that are not processed by a program.

For this dialog box, if you click "continue", the program may continue to run, but it may be in an unstable state. Click "exit" to exit the program immediately and unconditionally, this may cause data not to be saved. [Yuan Yongfu copyright]

Once a system-level error dialog box is displayed, the stability and reliability of the program are very poor. Avoid this situation as much as possible. In this case, you need to add exception handling to some appropriate methods in the call stack to handle exceptions thrown by the underlying method.

InC #Use"ThrowThe above keyword is thrown, and the following code demonstrates throwing an exception.

Public IntF1 ()

{

Throw New Exception("An exception occurred");

}

This method is usedThrowKeyword throws an exception. InC #All exceptions are thrown by an underlying method.

NoteF1Return an integer if the method body does not containReturnStatement compilation fails,ThrowStatement.

InC #Use"Try {} catch {} finally {}The following code demonstrates how to handle exceptions.

Public VoidHandleexception (IntA,IntB)

{

Try

{

//Enter the status where exceptions can be captured

F1 ();

}

Catch(ExceptionEXT)

{

//If an exception occurs, capture the exception here and execute this code

System. Windows. forms.MessageBox. Show (ext. Message );

}

Finally

{

//This code runs no matter whether an exception occurs.

Console. Writeline ("Processed");

}

}

In the keyword"Try"The code block after is generally placed as the functional code of the method. At this time, the system checks whether an exception is thrown. if an exception is thrown, It is captured immediately and then jumps to the keyword"Catch. The keyword"FinallyThe code block will be executed later. This code is generally used for the aftermath of this method, such as releasing important resources applied during the work process.CatchBlock andFinallyThe block is optional and can also be written as"Try {} catch {}"Or"Try {} finally {}". [Yuan Yongfu copyright]

ForTry {} catch {}"Structure, the program will capture and handle the exception, so that the exception will not be accessed.

ForTry {} finally {}"Structure, the program will perceive exceptions and perform some processing, but will not capture exceptions, the exceptions will continue to petition.

With exception handling, the exceptions thrown by the underlying method can be processed in a timely manner instead of being pushed all the way.. NetFramework becomes a system-level error. Therefore, appropriate exception handling must be added during program development.

Because exceptions are passively handled errors and the execution process consumes a lot of resources, it is always better to actively defend against errors than to passively handle errors. In practice, we can consider using both of them to make double insurance, so that the program can be reliable and stable. [Yuan Yongfu copyright]

 

Using Syntax structure

InC #Medium, keywordUsingYou can also useUsingStructure to implement certain exception handling. The syntax structure is"Using (){}". For example, the following code demonstratesUsingStructure.

Using(System. Io.FilestreamStream

=NewSystem. Io.Filestream("C: \ a.txt", System. Io.Filemode. Create ))

{

Stream. writebyte ((Byte) 2 );

}

In the field code,UsingOpen the file in the brackets behind it and create a file stream object. Then, output a byte to the file in the code block in the brackets, and there will be no other code.

File stream is a very important resource. It must be closed after being opened. Otherwise, the resource will be leaked. In the above Code, add the code"Stream. Close ()To close the file stream. But in fact, the code above is safe and there will be no resource leakage issues, becauseUsingSyntax structure.

The above code is equivalent to the following code:

System. Io.FilestreamStream

=NewSystem. Io.Filestream("C: \ a.txt", System. Io.Filemode. Create );

Try

{

Stream. writebyte ((Byte) 2 );

}

Finally

{

(System.Idisposable) Stream). Dispose ();

}

C #The compiler willUsingStructure translation into a"Try {} finally {}"Structure, and inFinallyBlock to callDisposeMethod to close the file stream and release all resources. Even if an error occurs in the function code and an exception is thrown, the file stream can still be closed to release resources.

From here we can see thatUsingThe syntax structure has a certain exception handling function. It does not capture exceptions, but can detect exceptions and perform some processing to reduce the negative impact of exceptions.

C # the syntax structure is for system. idisposable interface, system. idisposable the interface declares only one member " void dispose () ", used to release the important resources occupied by objects. Any implementation of system. idisposable interface objects can all be used using structure, such as file streams, database connections, and network connections. [Yuan Yongfu copyright]

Related Article

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.