Exception Handling details

Source: Internet
Author: User
Tags finally block
How to handle exceptions

As a developer, you should feel the advantages of constructing a structured exception handling mechanism through try, catch, and finally blocks .. The. NET Framework provides a large number of exception handling levels to handle different types of exceptions. All exceptions are inherited from the exception (base class ). You can implement custom error handling through inheritance to extend the exception handling mechanism. Unfortunately, many developers misuse this architecture capability. What you need to remember at any time is how an exception works when it occurs (in this architecture? Generally, there are three situations:

    1. Ignore the exception and let it rise in the call stack and be caught by other catch blocks.
    2. Capture exceptions for your application at the same timeProgramExecute necessary actions if you do not want to throw an exception again.
    3. Capture exceptions and overwrite them with other exceptions. This is more closely related to your application. Exception coverage is designed to avoid breaking the abstract hierarchy in the architecture. You can use the exception you throwInnerexceptionAttribute specifies what the original exception is, so that you can overwrite your existing exception with a new exception (more related to your system ). To understand exception overwriting, let's look at a method that can cause an ioexception. You can use loadingexception or failtoloadinfoexception at the application level to overwrite the original ioexception, this is better than giving users the underlying ioexception.

 

The exception handling framework of an application should have the following (requirements ):

    • Detection exception;
    • RunCodeClear;
    • Internal exception coverage;
    • Internal exception replacement;
    • Record and report error information;
    • Establish events that can be monitored externally to help system operations;

 

At the beginning, you should establish a consistent and Robust Exception management architecture. In all your systems, you should well encapsulate and abstract details such as their records and reports.

Good habits

Some good tips/suggestions are listed below for your reference in (Design) exception handling (time:

    • Throw an exception at a lower cost. Therefore, you should try your best to handle exceptions in the case of "exceptions". do not control the formal logical process. For example, the following code:
Void Empexits ( String Empid)
{
// Search for employee
If (Dr. Read (empid) =   0 ) // No record found
{
Throw ( New Exception ( " EMP not found " ));
}
}

Use the following code: Bool Empexits ( String Empid)
{
// Search for employee
If (Dr. Read (empid) =   0 ) // No record found
{
Return   False ;
}
}

 

    • Avoid capturing exceptions in the loop. If you want to capture exceptions, place the entire loop in the try/Catch Block.
    • Use the standard try/catch/finally exception handling method, which is recommended in managed code. The finally block ensures that all resources in the exception event are released.
      For example:
Sqlconnection Conn =   New Sqlconnection ( " " );
Try
{
Conn. open ();
// Some operation
// Some additional operations
}
Catch (Exception ex)
{
// Handle the exception
}
Finally
{
If (Conn ! =   Null   && Conn. State = Connectionstate. open)
Conn. Close (); // Closing the connection
}

 

    • Verify the code as much as possible to avoid exceptions. If you know that an inevitable condition may appear, avoid it. For example, check the null value (nothing in VB) before performing any operation to avoid usage exceptions and performance problems.
      Run the following code:
Double Result =   0 ;
Try
{
Result = Firstval / Secondval;
}
Catch (System. Exception E)
{
// Handling the zero divided exception
}

Should be replaced: Double Result =   0 ;
If (Secondval ! =   Null   && Secondval >   0 )
{
Result = Firstval / Secondval;
}
Else
{
Result = System. Double. Nan;
}

 

    • Do not throw an exception for unnecessary situations (Original: reasons. The overhead of throwing an exception again is the same as the overhead of instantiating a new exception. At the same time, throwing an exception again makes debugging more difficult. For example:
Try
{
// Perform some operations, in case of throw an exception...
}
Catch (Exception E)
{
// Try to handle the exception with E
Throw ;
}

 

    • The recommended method to handle different errors is to implement a series of catch blocks, which seems to be nothing, but can make your exception handling go from special to normal. For example, capturing a file-related exception is much better than capturing a filenotfoundexception, directorynotfoundexception, securityexception, ioexception, unauthorizedaccessexception, or even the last base class exception.
    • Ado. net errors should be handled through sqlexception or oledbexception.
    • Using the connectionstate attribute to check whether the connection is available is much better than exception handling.
    • Try/finally is often used, and finally provides the opportunity to close the connection. The Using statement can achieve the same effect.
    • Use the specified handler to handle exceptions. In some cases, if you know some possible exceptions, use the corresponding Exception Processing class, such:

 

Try
{

}
Catch (Sqlexception sqlexp) // Specific exception handler
{

}
Catch (Exception ex) // Generic exception handler
{

}

 

    • Your exception handling architecture should be able to detect exceptions and overwrite them internally, or replace them with other exceptions, or record and report such information for the monitoring system.
    • We recommend that you use the exception management application block provided by the Microsoft's patterns & Practices Team. This is a simple and scalable framework used to record exception information to the Event file. You can customize it to record logs to other data sources without affecting your system code. Exception management application block is a good code developed by the patterns & Practices Team and has been thoroughly tested by Microsoft labs.

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.