Notes for exception handling in ASP. NET, asp.net Exception Handling

Source: Internet
Author: User

Notes for exception handling in ASP. NET, asp.net Exception Handling

I. Four exceptions to be thrown in ASP. NET

 

1. If the code is run, causing memory leakage, resource unavailability, or the application status cannot be restored, an exception is thrown. The Console class has a lot of code similar to this:

If (value <1) | (value> 100 ))
{
Throw new ArgumentOutOfRangeException ("value", value, Environment. GetResourceString ("ArgumentOutOfRange_CursorSize "));
}
 

2. When an exception is captured, an exception is thrown if more useful information needs to be encapsulated. This type of exception is particularly useful at the UI Layer. The Message caused by system exceptions tends to be more technically described. On the UI Layer, the abnormal user may be the end user. If we need to present the exception Message to the end user, it is better to wrap the exception and then cause a new exception containing friendly information.

3. If the underlying exceptions do not make sense in the context of high-level operations, you can consider capturing these underlying exceptions and triggering new meaningful exceptions. For example, an InvalidCastException is thrown as a new ArgumentException.

4. Capture the underlying API error code and throw it. The Console encapsulates the error code returned by calling the windows api and causes the code to throw a new exception.

 

Ii. exceptions inherent in ASP. NET


1. Exception: The base class of all Exception objects
2. base classes of all errors generated during SystemException running
3. IndexOutOfRangeException is triggered when the subscript of an array exceeds the range
4. NullReferenceException thrown when an empty object is referenced


5. InvalidOperationException: when a call to a method does not take effect for the current state of the object, it is triggered by some methods.
6. base classes with all ArgumentException parameter exceptions
7. ArgumentNullException is triggered by the method when the parameter is null (not allowed ).
8. ArgumentOutOfRangeException is triggered by the method when the parameter is not within the specified range.


9. base class of the InteropException target or the exception that occurs outside the CLR Environment
10. An exception occurs when ComException contains the HRESULT information of the COM class.
11. SEHException encapsulate win32 structure Exception Handling Information exceptions

 

Iii. Notes for exception handling in ASP. NET

 

1. Avoid writing Invalid code in finally

You should always think that the finally internal code will be executed before the return method, even if the return is in the try block. However, it is necessary to distinguish between referenced type variables and value type variables in finally, which will lead to different results.

For example

C # code Replication
Private static int TestIntReturnInTry () {int I; try {return I = 1;} finally {I = 2; Console. writeLine ("\ t change int result to 2, finally executed ");}}

 

It returns 1. In the code, I = 2 is actually an invalid piece of code. If the compilation adopts the Release mode, the compiler will directly Delete I = 2, and it will not generate the corresponding IL code for it.

 

However:

 

C # code Replication
Static User TestUserReturnInTry () {User user User = new user () {Name = "Mike", BirthDay = new DateTime (2010, 1, 1)}; try {return User ;} finally {user. name = "Rose"; user. birthDay = new DateTime (2010, 2, 2); Console. writeLine ("\ t set user. change Name to Rose ");}}

In the User returned by TestUserReturnInTry, the value of Name has changed to Rose.

 

2. Avoid nested exceptions

Exceptions should be allowed to spread up in the call stack. Do not use catch too much and throw again. We need to avoid nested exceptions for no reason.

 

3. Avoid "eat" exceptions

To avoid the "eat" exception, it does not mean that the "eat" exception should not be avoided, but there is an important principle: this exception is sadly foreseen, and it is generally not a Bug.

Imagine that you are decrypting tens of thousands of files. These files come from different clients and may be damaged by file times. Your goal is to insert the decrypted data into the database. At this time, you have to ignore the decryption failures and let the process proceed. Of course, it is necessary to record logs, because in the future, you may perform unified processing on files that fail to be decrypted.

In another case, you may not need to record logs. In a distributed system that controls thousands of controlled terminals, the control end needs to send heartbeat data to determine the online status of the controlled end. The common practice is to maintain a semaphore. If the sending of Heartbeat Data fails at an acceptable blocking time such as 500 ms, the control thread will not receive the signal, you can determine the disconnection status of the controlled end. In this case, it is usually meaningless to record each SocketException.

If you do not know how to handle an exception, do not "eat" the exception. If you "eat" an exception that should have been passed online, a BUg may be generated here, in addition, it will be very cost-effective.

 

4. Avoid record exceptions at a lower position of the Call Stack

The most suitable for exception recording and reporting is the upper layer of the application, which is usually the UI Layer. If such an application exists, its BLL layer may be called by a Winform window program or a console application, if the BLL module reports an exception to the Administrator, you do not know whether to use the MessageBox method or Console. write method.

If an exception is recorded or reported at a lower position of the Call Stack and thrown again after being packaged, repeat the record.

 

5. Do not derive an exception from the base class System. ApplicationExcetipn.

Microsoft has fixed this point by itself. The current suggestion is to derive an Exception from System. Exception or one of other common basic exceptions. In fact, if you enter Excetion in Visual studio and then press the shortcut key tab, vs will automatically create a custom Exception class that inherits from System. Exception.

 

4. Other suggestions for exception handling in ASP. NET

 

1. provide meaningful text when exceptions are thrown.
2. to cause an exception, only when the condition is true, that is, when a normal return value is not met.
3. If your method or attribute is passed with a bad parameter, an ArgumentException exception is thrown.


4. When the call operation is not suitable for the current state of the object, an InvalidOperationException must be thrown.
5. The most suitable exception should be thrown.
6. Link exceptions are used, which allow you to track the exception tree.


7. Do not use exceptions for normal or expected errors.
8. Do not use exceptions for normal flow control.
9. Do not cause NullReferenceException or IndexOutOfRangeException in the method.


Exception Handling in aspnet

Why do you want to add
Try
{}
Catch
{
} Statement,
No ..

How to Use throw in aspnet program exception handling, and how to do it after throw, for example, to explain

String input ....

Try {
If (input = null)
{
Throw new NullReferenceException ("the input is empty ");
}
Else
{
// Do...
}
}
Catch (NullReferenceException ex)
{
// Catch the exception thrown above and handle it here
}
Cath (Exception e)
{
// Any other exceptions
}

When an exception is thrown, go to the corresponding catch to handle the exception!

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.