Correct use of the exception exception object

Source: Internet
Author: User

First, the composition of the anomaly

New Exception () Create exception object

Throw throws Exception object (main performance loss location)

try{}catch{} Catching Exception objects

C # Inside the exception object is divided into two sub-classes ApplicationException, SystemException, the former is mainly provided to the application custom exception class, which is provided to the system-defined exception class

Second, how to use the exception

The normal logic of the exception is: thrown from the bottom, handled by the upper layer

1, the underlying method or provide to others to use some parameter filtering or other exceptions in the method should be thrown up

such as (learn from out-of-the-box code lazy Write):

 Public void insertuser (user user) {     if(user==null)    {        throwNew ArgumentNullException (" parameter user is null");    }     // invoke ORM    }    

2, the upper layer should be added try{}catch{} to catch the exception and processing

Such as:

Try {    BLL. Insertuser (null);} Catch (ArgumentNullException e) {    loghelper.write (e.message);}

3, avoid some wrong way of handling the exception

such as (learn from out-of-the-box code lazy Write):

/*Verify the Legality of user input with exception validation is part of the business logic, absolutely do not use exception to deal with, note, is user input, so this experience is limited to the performance layer logic*///Typical error 1Try{    intI=int. Parse (TextBox1.Text);}Catch(Exception ex) {alert ("Do not enter non-numeric");}//Typical error 2voidValidateInput (inti) {    if(i<0&&i> -)    {        Throw NewException ("input data range error"); }}/*To give the exception to the underlying processing this error is to completely do not validate the user input and direct data validation thrown 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*///Typical error 3Try{    stringname=request.querystring["xx"]; List<User> userls=user.queryuserbyname (name);}Catch(SqlException ex) {}/*It is certainly a very brain-crippled decision to produce this error entirely without an abnormal mechanism. However, many times some people do not understand the abnormal mechanism, because of the abnormal performance cost of fear, often make such a brain residual decision 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 .*///Typical error 4 Public BOOLInsertuser (User user,ref intErrcode) {     if(user==NULL) {Errcode= the;//the code for the null error of the argument return false;    }    //Invoke ORM}

Third, abnormal performance test

Conclusion:

1, new Exception () exception object and create normal object performance loss is not much different

2, throw throw exception will cause system performance loss, mainly in "Fill the stack Information", "Record exception snapshot" and so on

3, try{}catch{} does not cause significant system overhead, plus no performance difference

4, the method provided by the outside as far as possible to throw an exception, to avoid the program crashes, please inherit ApplicationException base class when using

5, the business logic data as far as possible with if{}else{} filter out, do not rely on the throw new Exception () to deal with

6, abnormal in the program can not be avoided, reasonable use to avoid program crashes is the only right way

(The above conclusions represent only personal views)

     Public classTyhtest {Private stringmsg;  PublicTyhtest (stringmsg) {             This. msg =msg; }    }     Public classtyhexception:applicationexception {//this notation is inherited from the base class construction method         PublicTyhexception (stringMSG):Base(msg) {}}classProgram {Static voidMain (string[] args) {            intMax = -; intj =1; stringstr ="a"; //==========Stopwatch time1 =NewStopwatch (); Time1.            Start ();  for(inti =0; i < Max; i++)            {                Try                {                    if(J >0&&!string. IsNullOrEmpty (str))Throw NewException ("Exception Exception"); }                Catch(Exception e) {}} time1.            Stop (); Console.WriteLine ("throwing exception exceptions takes time:"+time1.            Elapsedmilliseconds); //==========Stopwatch time2 =NewStopwatch (); Time2.            Start ();  for(inti =0; i < Max; i++)            {                Try                {                    if(J >0&&!string. IsNullOrEmpty (str))Throw NewApplicationException ("Exception Exception"); }                Catch(ApplicationException e) {}} time2.            Stop (); Console.WriteLine ("throwing ApplicationException Exceptions takes time:"+time2.            Elapsedmilliseconds); //==========Stopwatch Time3 =NewStopwatch (); Time3.            Start ();  for(inti =0; i < Max; i++)            {                Try                {                    if(J >0&&!string. IsNullOrEmpty (str))Throw NewTyhexception ("Exception Exception"); }                Catch(Exception e) {}} time3.            Stop (); Console.WriteLine ("Throwing Custom Tyhexception exceptions takes time:"+Time3.            Elapsedmilliseconds); //==========Stopwatch Time4 =NewStopwatch (); Time4.            Start ();  for(inti =0; i < Max; i++)            {                Try                {                    if(J >0&&!string. IsNullOrEmpty (str)) {}Else                    {                    }                }                Catch(Exception e) {}} time4.            Stop (); Console.WriteLine ("do not throw anomalies with if time-consuming:"+Time4.            Elapsedmilliseconds); //==========Stopwatch Time5 =NewStopwatch (); Time5.            Start ();  for(inti =0; i < Max; i++)            {                Try                {                    varTest =NewTyhtest ("Creating Objects"); }                Catch(Exception e) {}} time5.            Stop (); Console.WriteLine ("creating a Normal object tyhtest time-consuming:"+Time5.            Elapsedmilliseconds); //==========Stopwatch Time6 =NewStopwatch (); Time6.            Start ();  for(inti =0; i < Max; i++)            {                Try                {                    varTest =NewException ("Create exception Object"); }                Catch(Exception e) {}} time6.            Stop (); Console.WriteLine ("creating an Exception object exception time-consuming:"+Time6.                        Elapsedmilliseconds);        Console.readkey (); }}

(Stopwatch does not need a lot of new, code copy and paste, please ignore, ignore, haha ~)

Correct use of the exception exception object

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.