Let's talk about abnormal things.

Source: Internet
Author: User
ArticleDirectory
    • The system throws an exception.
    • The user throws an exception.
    • Example of correct Exception Handling
    • Example of Exception Handling
Preface

First, this article explains my own understanding of exceptions, and summarizes my own practices and network experience.

The second is the purpose of this article, which is due to the re-exploration of try ...... I have no objection to the results of the catch performance issue, but its argument is true. Therefore, I will discuss it in this article.

Exception

Many people blur the exception when discussing it, as if the so-called exception is try {} catch {}. The exception is exception, which is a very one-sided problem. As a result, exceptions affect performance ...... And so on. Below, I will strictly divide the broad and misinterpreted word.

Exception Mechanism

The so-called exception mechanism means that the language platform supports the mechanism of exception handling mode, such as the exception object in C #, try {} catch {} finally {} structure, throw throws exception statements, and so on, are implemented in C.

The exception mechanism exists along with the language. Since a language supports the exception mechanism, exceptions are unavoidable. Even if you do not throw the exception yourself, you use the system class, it will also throw an exception to you, so it is very important to discuss how to use the exception in the system.Ridiculous. The exception mechanism is like a system backdoor. When a system error occurs during execution of a process or you think the system is abnormal, you can take a snapshot of the current situation to generate an exception object, the method for calling this process is notified through a special channel.

Exception object

The exception object is used in the exception mechanism to describe the exception and record the error information. It can be said that it is a snapshot of the error, which is similar to the photo taken by the sky when the red light is opened.

Throw an exception

The so-called throw exception is a means of notifying the call method in the exception mechanism that the method has an error. Throws exceptions are also the impact of exceptions on performance, because the overhead of system performance is caused by exceptions.However, throwing an exception cannot be avoided because it is a feature of the system itself. If you do not throw an exception, the system itself throws it. Once the system throws an exception object, how do you avoid this performance overhead?No

For example, if method A calls Method B and method B accesses the database, and an error occurs, Method B throws an exception and method A needs to catch the exception to handle it.

An exception is thrown in two forms. One is an exception thrown by the system, and the other is an exception that we think when processing a logic error, we can throw an exception object, to notify the method to call this method. An error occurred here.

The system throws an exception.

The exceptions thrown by the system are transparent to programmers, that is, we do not need to care about how the system knows the errors, once an error occurs in the system library, the exception object will be thrown to the method we call it, because the system itself does not know how to handle this error.

The user throws an exception.

When a user throws an exception, he usually writes a class library and defines an API for use by others. At this time, we do not know how to handle these logical errors, therefore, you need to give a method to know how to handle logical errors.

In C #, an exception object is thrown by defining the throw keyword. In addition to the newly created exception object, you can throw the caught exception again. If you do not know how to handle this exception, it is a good habit to throw the exception again because the performance has been compromised since the exception has been thrown, so I don't care about how much it means to better recover the wrong results.

Exception Handling

All exceptions must be properly handled, that is, you must handle all exceptions. An exception is thrown when a system error occurs. This is something in C # that cannot be avoided. Therefore, try {} catch {} is everywhere in the system {}.

However, try {} catch {} itself does not affect the system performance, so when no exception occurs, try {} catch {} will not slow your system down, in the event of a system exception, the system will crash if you don't handle it. Are you willing to slow down the system a little bit and then handle this error, or are you willing to crash the system?

For Exception Handling, I think Java is more strict, and it is better to strictly declare and handle all exceptions. This forces you to pay attention to exceptions, in this case, the system crashes before you think that you have not handled this exception.

 

How to handle

How can I handle exceptions correctly? This is a lot of C #ProgramThe topic that people don't finally understand. what many people know is simply not to use exception handling as the business logic, but what it means to use exceptions to process the logic is unknown. Here I will explain in detail where exceptions are to be used and where exceptions are to be used.

First, there is a premise that the exception mechanism is a bottom-up bubble process, so the normal logic is that the exception is thrown by the bottom layer and handled by the top layer.

Example of correct Exception Handling

To compile a robust reference program, ensure that all system exceptions must be handled, that is, exceptions that may be thrown when the. NET class library method is called.

Example:

As we can see, the getresponse method throws two exceptions: invalidoperationexception and webexception. Then we need to callCodeThe catch handles these two exceptions separately.

If you do not know how to handle this exception in this method, for example, this method cannot be mounted, and it is separated from the presentation layer by several layers, however, if you need to notify the user at the performance layer or decide whether to notify the user or quietly enter the village, or retry the attempt, what you cannot decide is to be handled by the upper layer.

Some may say. net can handle exceptions in a unified manner. However, I do not recommend the large and comprehensive processing method, which is not detailed enough. In many cases, you may find the source of the error due to strange errors. For example, you cannot try again in case of network problems.

The exception must be handled nearby to facilitate tracing. It is important to note the location where the "XXX method has failed". This description can reduce the number of detours during system troubleshooting, write details as much as possible.

If your code is used by other programmers rather than directly interacting with the end user, in addition to handling all exceptions thrown by the system, you also need to use exceptions to verify the filter entry parameters. For example, suppose you want to provide other programmers with a method to insert user objects into the database:

   Public     Void  Insertuser (User user ){  If  (User  =  Null  ){  Throw    New  Argumentnullexception (  "  The user parameter is null.  "  );}  //  Call ORM    } 

Here we have verified the entry parameters and throw an exception as soon as possible, because the exception thrown here and the db operation such as not processing throws an exception, it must be that the manual throw overhead here is smaller. The principle here is that if this parameter causes a direct error in the underlying code, you should handle it nearby, rather than letting it throw system exceptions at the underlying layer. Of course, there is another principle: Do not judge the business logic here. For example, in the above example, do not verify whether the value of the user attribute is legal or not.

 

Example of Exception Handling

1: Verify user input with exceptions

The legality verification of user input is part of the business logic. Do not handle exceptions. Note that it is user input. Therefore, this experience is limited to the logic of the presentation layer.

Typical error 1:

 
Try{IntI=Int. Parse (textbox1.text );}Catch(Exception ex) {alert ("do not enter a non-number ");}

Typical error 2:

 Void Validateinput (  Int  I ){  If  (I  <  0  &&  I  >  100  ){  Throw     New  Exception (  " Input data Range Error  "  );}} 

 

The preceding two errors are typical errors,

2: delay the exception to the underlying layer

We mentioned this in the correct example.

Typical error 3:

   Try  {  String  Name  =  Request. querystring [  " Xx  "  ]; List  <  User  >  Userls  =  User. queryuserbyname (name );}  Catch  (Sqlexception ex ){} 

This error is caused by directly throwing data verification to the database without verifying the user input. It is a fatal error when the database reports an error to determine whether the user input is correct, many injection vulnerabilities are generated as a result.

3: no exception mechanism is required.

This error is definitely caused by a very brainless decision. However, many people who do not know the exception Mechanism often make such a decision due to fear of exceptional performance overhead.

Typical error 4:

   Public     Bool  Insertuser (User user,  Ref     Int  Errcode ){  If  (User  =  Null  ) {Errcode =  110  ;  //  Code with null parameter error      Return     False  ;}  //  Call ORM    } 

It seems that the performance was high when I went back to liberation overnight. But what should I do if the system is abnormal? Once a database error occurs, the system crashes. Some experienced people may say that I will put the following try {} catch {} Up, but isn't that just taking off my pants and farting? All exceptions are thrown, and the overhead has already been generated, the result is that the system logic is malformed at the expense of the rich information of the exception object. Performance has not been improved.

Impact of exceptions on Performance

The exception mechanism is a feature of C #, which makes it impossible for you to escape. Therefore, it is nonsense to discuss the overhead caused by exceptions. There is no necessary research to fundamentally resolve the problem. We should be clear about the impact of exception throws on the system and how to reduce unnecessary performance consumption on the basis of ensuring system robustness.

1. The exceptional performance overhead increases with the increase in the call stack depth.

Comparison test:

Test code 1

 Stopwatch SW  =     New  Stopwatch (); Sw. Start ();  For  (  Int  I =     0  ; I  <     10  ; I  ++  ){  Try  {  Throw     New  Exception (  " Test  "  );}  Catch  {}} Sw. Stop (); MessageBox. Show (SW. elapsedmilliseconds  +     "  MS  "  ); 

Test results:

Number of calls First time Second Third time Fourth
Time

 

Test code 2

 Stopwatch SW  =     New  Stopwatch (); Sw. Start ();  For (  Int  I  =     0  ; I  <     10  ; I  ++  ){  Try  {System. Io. file. openread (  " C: \ nonexistent txt.txt  "  );}  Catch  {}} Sw. Stop (); MessageBox. Show (SW. elapsedmilliseconds  +     "  MS  "  ); 

 

Test Results

Number of calls First time Second Third time Fourth
Time

Conclusion: we can find that the performance overhead increases as the call stack goes deeper, so exceptions should be thrown as soon as possible.

2. Strictly check the input data in the business logic.

3.Try {} catch {} does not cause any system overhead. Throw throws an exception.This is repeatedly emphasized.

For example:

This kind of comment is completely brainless.

 

 

Conclusion

 

The exception mechanism is the built-in error handling mechanism of C #. The only correct way to avoid it is to learn how to use it correctly.

I hope everyone can use the exception correctly and study every day.

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.