"C # Advanced Series" 19 exception and state management

Source: Internet
Author: User
Tags finally block throw exception

An exception is an action declared by a member without completing its name.

     Public class Girl {        publicstringgetset;}    }      Public class troy{       Girl Girl;         Public void Love () {        Console.WriteLine ("Troy  ") + girl. Name);       }    }

The above code will have an exception, because Troy to execute the Love function, but girl there is no assignment at all. Originally Troy expected to complete love a girl This action, the result of something unusual, the girl left the Troy.

Issues to be solved by exceptions

Many behaviors (such as methods and properties) are often not able to return error codes (such as void methods, constructors, property acquisition settings), but they still need to report errors, and the exception is to solve the problem.

That is, the exception handling mechanism is actually to return a predictable error code, rather than to catch an unknown exception so that the program does not error. (This is very important)

Do not let the program swallow abnormal, do not expose the exception to keep it running, but it may make the program to make a more wrong move. (change it, don't hide it)

So in fact, I have just studied the time has been a question, I this system a lot of people in use Ah, if you do not swallow abnormal, the newspaper yellow Pages is not more 6?

Now I think this is not contradictory, if there is an exception in the catch after the exception processing restore operation, and then write the log or use a unified page to prompt the user error, rather than the yellow pages to the user to see. (Just like you tell someone you have a stomach problem, say it in your mouth and body language, you open your belly and tell people you're sick is your fault.)

. NET exception handling mechanism

. NET exception handling mechanism is built on the structured exception handling mechanism (structured Exception handing, or SEH) provided by Windows.

Exception-handling code does not demonstrate, say three chunks

  • Try Block
    • A try block should be divided into two try blocks if it can throw an operation of the same exception class, but with different exception recovery measures.
    • Try and finally come together to perform a resource cleanup operation (or use a using OH).
  • Catch block
    • A try block can correlate 0 or more catch blocks.
    • A catch followed by an expression in parentheses is called a snap type, and the exception snap type must be System.Exception or its derived class.
    • The CLR searches for exceptions from top to bottom, so you want to put more specific exceptions at the top. This means that the most derived exception is written first, then the base class, then the System.Exception or no catch block of any catch type is specified.
    • If the thrown exception is not caught, that is, none of the catch's type matches the thrown exception, the CLR goes back to the higher stack of the call to search for the catch type that matches the exception. An unhandled exception occurs if the top of the call stack is not matched to a catch block. Once a matching catch block is found, the code for all finally blocks in the inner layer is executed, otherwise the code of all finally blocks in the inner layer will not execute. This means that the exception is reported in the following sample code:
      Static voidMain (string[] args) {            Try{Funca (); }            finally{Console.WriteLine ("Main function finally");        } console.read (); }        Static voidFunca () {Try{Object obj=NewDateTime (); intA = (int) obj;//We're going to report system.invalidcastexception anomalies .            }            Catch(invaliddataexception)//represents a mismatch, and then to the upper level of the call stack is the main function, but the try in the main function has no catch at all, so much less a match, i.e. an unhandled exception occurred            {                //There's absolutely no execution here .            }            finally{//Although there is finally a good deal, whether or not the exception will be executed, but at this time the above exception is not catch,
      So the error has been abnormal, will not be carried out here. At this point the CLR terminates the process, which is better than making the program continue to run with unpredictable resultsConsole.WriteLine ("finally of function a"); } }
    • There are three ways to handle the end of a catch block:
      • Re-throw the same exception, to call the stack layer of code to notify the occurrence of the exception, that is, throw;
      • throws a different exception to the call stack layer of code to provide richer exception information, that is, throw ex;//here ex for the new exception object
      • Let the thread exit from the bottom of the catch block without throwing an exception to the higher level.
    • The code can enlist the FirstChanceException event of the AppDomain so that it is notified whenever an exception occurs in the AppDomain and calls these event callback functions before the CLR starts searching for any catch blocks.
  • Finally block
    • The finally block is the code that guarantees execution.
    • If an exception is thrown inside and finally inside the catch, the exception in the try is not logged and the information is lost.

System.Exception class

Microsoft stipulates that all CLS-compliant programming languages must throw and catch exceptions derived from that type.

In general, there are also three attributes to note in this class:

    • Message indicates why the exception was thrown
    • InnerException if the current exception is thrown while handling an exception, then the innerexception is the previous exception. With the public method GetBaseException, you can traverse the inner exception list to return the exception that was originally thrown.
    • StackTrace contains the names and signatures of all methods that were called before the exception was thrown. It returns all the methods from the exception throw position to the exception catch unknown.

Throw exception

There are two issues to consider when throwing exceptions:

The first is an exception that throws what type of exception. You should choose a more meaningful type. To take into account the high code in the call stack, know how the code determines that a method fails to execute a decent recovery code. The author strongly recommends that the inheritance hierarchy of exceptions be shallow and wide, so that you can create as few base classes as possible. The base class means that many errors are treated as an error.

The second is what string messages are passed to the constructor of the exception type.

Custom exception Classes

It looks like the custom exception class is simple, just inheriting the System.Exception class is OK, but actually it's a tedious thing to do.

Because all classes derived from the System.Exception class should be serializable, allowing them to cross the AppDomain boundary to write to the log or database. And serialization involves a lot of problems.

The author wrote a generic exception class to simplify, I do not write here, in fact, in the format of a system to find an exception to write on the line:

Don't forget to add the [Serializable] attribute to the custom class.

The author's play is more high-end, he built a generic exception class inherits exception, and then writes some constructors or serialization functions in this class. The personalization exception information is used as a generic variable t to the generic exception class, which simplifies the function.

------Not to be continued, the above is still some basis, the next will write how to use the exception handling mechanism correctly---------

Reliability in exchange for development efficiency

Design specifications and Best practices

Unhandled exception

To debug an exception

Performance issues with exception handling

Constrain execution Area

Code contract

"C # Advanced Series" 19 exception and state management

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.