C # Exception Performance impact

Source: Internet
Author: User

What is an exception

Many people in the discussion of abnormal time is very vague, as if the so-called exception is try{}catch{}, the exception is exception, very one-sided, so the abnormal impact performance, XXXX ... And so many strange remarks, so I intend to justify the exception. Below, I will be the exception of this very broad, easy to misinterpret the word is strictly divided.

Exception mechanism

The so-called anomaly mechanism also refers to the language platform to support the exception of this error-handling mode mechanism, such as C # exception object, try{}catch{}finally{} structure, throw throw exception statement, and so on, are the C # language in the implementation of the exception mechanism.

Exception mechanism is the existence of language, a language since the support of the abnormal mechanism, then the exception is unavoidable, even if you do not throw an exception, you use the system class, will throw an exception to you, so it is very ridiculous to discuss in the system with no exception is very funny . The anomaly mechanism is like the back door of the system, when a system error occurs during a process execution, or when you think that the system is not functioning properly, take a snapshot of the situation at that time to generate an exception object and notify the method of invoking the process through a special channel.

Exception Object

The exception object is the exception mechanism used to describe the exception, log the error message, can be said to be a snapshot of the error, as you drive fast running red light is taken by the eyes of the picture.

Throw exception

The so-called throw exception is the method of notification invocation in the exception mechanism. Throwing exceptions is also where a lot of people are criticized for their performance impact, because the overhead of system performance is caused by throwing exceptions. but throws the exception also cannot avoid, because this is the system itself characteristic, you do not throw the exception, the system itself also throws, once the system throws the exception object, how can you avoid this performance overhead? No

For example, method A calls method B, method B accesses the database, an error occurs, then B throws an exception, and a is required to catch the exception to handle.

There are two forms of throwing exceptions, one is the exception thrown by the system, and the other is that we think that when we are dealing with a logic error, we can throw an exception object to notify the method that called the method, and there is an error.

System throws an exception

The exceptions thrown by the system are transparent to programmers, that is, we don't need to be concerned about how the system learns that something went wrong, and the System class library throws the exception object to the method we call it when it goes wrong, because the system itself does not know how to handle the error.

User throws an exception

User-thrown exceptions are usually used when writing a class library, defining a set of APIs for others to use, and at this point we don't know how to handle these logic errors, so we need to deal with methods that know how to handle logic errors.

The exception object is thrown in C # by defining the Throw keyword, which, in addition to throwing the newly created exception object, can be re-thrown by the exception that was already catch. If you do not know how to handle this exception, it is a good habit to re-throw the exception, because since the exception has been thrown, then the performance has been lost, so do not care more so much to better restore the wrong results.

Handling Exceptions

All exceptions must be handled properly, i.e. you must handle all exceptions. Because the system error is thrown out of the exception, so this is the C # bones of things, can not be avoided, so the system will be flooded with try{}catch{}.

But try{}catch{} itself does not affect the performance of the system, so when no exception occurs try{}catch{} will not make your system slow, and once the system anomalies, you do not deal with the system crashes, Do you want the system to slow down a little bit and get rid of the error or do you want the system to crash?

In the case of handling exceptions I actually think that the Java kind of stricter, requires strict declaration and handling of all exceptions in a better way, can force you to pay attention to the exception of the matter, lest the system crashes to remember that you did not deal with this exception.

How to Handle

How do I handle exceptions correctly? This is a topic that many C # programmers have not finally figured out, and what many people know is not to use exception handling as business logic, but it's unclear how to handle logic with exceptions. Here I would like to explain in detail, where to use the anomaly, where not to use.

First there is a premise, the anomaly mechanism is a bottom-up bubbling process, so the normal logic is that the exception is thrown from the bottom, handled by the upper layer.

Example of handling exceptions correctly

To write a robust reference program, you must first ensure that all system exceptions, called calls, are handled. NET class Library method, this method may throw an exception

Cases:

We can see that the GetResponse method throws two exceptions InvalidOperationException and WebException. Then we need to handle the two exceptions separately from the catch where the code is called.

If you do not know in this method how to deal with this anomaly, such as this method flattening out, and the presentation layer away from several layers, but also need to inform the user in the performance layer or the upper business to inform the user or quietly into the village, or quietly try again, Then things that you can't decide are going to be left to the top.

One might say. NET can handle the exception uniformly, but I do not recommend that kind of chatty processing, not careful enough, many times you will be surprised by the error of the source of the error you are tracking. And, for example, encountering network problems retrying can not be processed.

Exception must be handled nearby, so as to facilitate tracing, and note that "XXX method error" That place, very important, this description can let you in the system when the wrong time to go a lot of detours, as far as possible to write detailed points.

If your code is used by other programmers instead of interacting directly with the end user, you will need to validate the filter entry parameters with exceptions in addition to handling all exceptions thrown by the system. For example, suppose you want to provide another programmer with a way to insert a user object into a database:

    public void Insertuser (user user)    {        if (user==null)        {            throw new ArgumentNullException ("parameter User is null") ;        }        Invoke ORM    }

Here we verify the entry parameters and throw out the exception as early as possible, because the exception thrown here and the non-processing DB operation throws an exception, it must be the cost of manually throwing here is smaller. One of the principles here is that if this parameter causes the underlying code to go directly wrong, then dispose of it at the nearest, rather than allowing it to cause system exceptions to be thrown at the bottom. Of course, there is a principle is not to judge the business logic here, such as the above example does not verify that the value of the user's property is not legal or the like.

Examples of handling exception errors

1: Verify user input with exception

The legitimacy validation of user input is part of the business logic, never use exception to handle, note, is user input, so this experience is limited to the expression layer logic

Typical error 1:

try{    int I=int. Parse (TextBox1.Text);} catch (Exception ex) {    alert ("Do not enter non-numeric");}

Typical error 2:

void ValidateInput (int i) {    if (i<0&&i>100)    {        throw new Exception ("Input data range Error");}    }

Both of these errors are typical of error-using exceptions,

2: Delay the exception to the bottom

We've mentioned that in the right example.

Typical Error 3:

        Try        {            string name=request.querystring["xx"];            List<user> userls=user.queryuserbyname (name);        }        catch (SqlException ex)        {        }

This error is to completely do not validate the user input and directly put the data validation into the database, waiting for the database error to determine the correctness of user input, this is a very fatal error, a lot of injection vulnerabilities are generated from this.

3: No abnormal mechanism at all

Producing this error is certainly a result of a very brain-crippled decision. However, many people who do not understand the abnormal mechanism often make such a brain-stump decision because of the fear of abnormal performance overhead.

Typical error 4:

    public bool Insertuser (User user,ref int errcode)    {        if (user==null)        {            errcode=110;//parameter is empty error code            return false;        }        Invoke ORM    }

Feeling is a night back to the liberation, performance is high, but how to do the system abnormal? Once the database has gone wrong, just wait for the system to crash. Some experienced said I would put the following try{}catch{} up, but that is not taking off the trousers fart, the exception is thrown, the cost has been generated, the result is to sacrifice the exception of the rich information of the object in exchange for the malformed system logic. Performance has not been improved.

Effects of exceptions on performance

The exception mechanism is the C # feature, so you can not escape, so the discussion of the exception to bring you a lot of costs are nonsense, there is no necessary research, fundamentally unable to solve the problem. What we should figure out is how the exception throws to the system, and how to reduce unnecessary performance consumption on the basis of ensuring the robustness of the system.

1. The performance overhead of the exception increases as the depth of the call stack increases.

Comparison test:

Test Code 1

            Stopwatch SW = new Stopwatch ();            Sw. Start ();            for (int i = 0; i < i++)            {                Try                {                    throw new Exception ("test");                }                Catch {}            }            SW. Stop ();            MessageBox.Show (SW. Elapsedmilliseconds + "MS");

Test results:

Number of Calls First time Second time Third time four times
Time

Test Code 2

           Stopwatch SW = new Stopwatch ();            Sw. Start ();            for (int i = 0; i < i++)            {                try                {                    System.IO.File.OpenRead ("c:\\ txt.txt not Present");                }                Catch {}            }            SW. Stop ();            MessageBox.Show (SW. Elapsedmilliseconds + "MS");

Test results

Number of Calls First time Second time Third time four times
Time

Summary: Thus we can see that as the call stack in depth, the performance overhead is also greater, so the exception should be thrown as early as possible.

2. The input data should be strictly checked in the business logic.

3.try{}catch{} does not cause any overhead, and the overhead is the throw throw exception , which is repeatedly emphasized

Such as:

This kind of speech is purely brain-crippled.

Conclusion

The exception mechanism is a C # built-in error-handling mechanism, and you can't avoid it, the only right way is to learn how to use it correctly

Reprint: http://www.mamicode.com/info-detail-99312.html

C # Exception Performance impact

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.