[C # advanced series] 19. Exception and status management,
An exception occurs when a member fails to complete the action declared by its name.
Public class Girl {public string Name {get; set ;}} public class Troy {Girl girl Girl; public void Love () {Console. writeLine ("Troy falls in love with" + girl. name );}}
The above code has an exception because Troy executes the Love function, but girl has no value assignment at all. Originally Troy expected to complete the action of loving a girl. As a result, something went wrong and the girl left Troy.
Issues to be solved
Many behaviors (such as methods and attributes) often fail to return error codes (such as void methods, constructors, and attribute acquisition settings), but they still need to report errors, then the exception is solved.
That is to say, the exception handling mechanism is actually to return predictable error code, rather than to capture unknown exceptions so that the program does not report errors. (This is very important)
Do not let the program swallow exceptions, do not expose the exceptions to continue running, but may make the program make more wrong actions. (If there are any mistakes, do not hide them)
As a matter of fact, I have always had a question when I was just learning. Many people are using this system. If you don't swallow the exception, isn't the yellow pages more than 6?
Now I think this is not a conflict. If an exception exists, it will be restored after the exception is caught, and then a log is written or a unified page will be used to prompt the user for an error, instead of showing the yellow pages to users. (Just like you tell others that you have a stomachache. You can use your mouth and body language to express your situation. If you open your stomach and tell others that you are ill, you are wrong)
. Net Exception Handling Mechanism
. Net Exception handling mechanism is based on the Structured Exception handling mechanism (SEH) provided by windows.
The exception handling code will not be demonstrated. Let's talk about three major parts.
- Try Block
- If a try block can throw an operation of the same exception class but requires different exception recovery measures, it should be divided into two try blocks.
- Try and finally are usually used to clean up resources (you can also use using ).
- Catch Block
- A try block can be associated with 0 or more catch blocks.
- Catch follows the expression in parentheses as the capture type. The Exception capture type must be System. Exception or its derived class.
- CLR top-down search exception, so you need to place more specific exceptions on the top. That is to say, first write the Exception with the largest degree of derivation, then the base class, and then the System. Exception or catch block with no capture type specified.
- If the thrown exception does not catch, that is to say, the catch type does not match the thrown exception, the CLR will go back to call the stack to search for the catch type that matches the exception. If no catch block is matched at the top of the Call Stack, an unhandled exception will occur. Once a matching catch Block is found, the code of all finally blocks in the inner layer will be executed, otherwise the code of all finally blocks in the inner layer will not be executed. In other words, the following sample code reports an exception:
Static void Main (string [] args) {try {FuncA ();} finally {Console. writeLine ("main function Finally");} Console. read ();} static void FuncA () {try {Object obj = new DateTime (); int a = (int) obj; // System is reported here. invalidCastException exception} catch (InvalidDataException) // indicates that the exception does not match, and then the upper level of the Call Stack is the main function. However, try in the main function does not have catch, so there is no matching, that is, an unhandled exception occurs. {// it will not be executed here.} finally {// although there is a Finally statement, it will be executed whether or not an exception occurs, however, the above exception does not catch,
// Therefore, an error has been reported and will not be executed here. At this time, the CLR will terminate the process, which is better than making the program continue to run and causing unpredictable results. Console. WriteLine ("function A Finally ");}}
- There are three processing methods at the end of the catch Block:
- Re-throw the same exception and notify the code at the higher layer of the call stack of the exception, that is, throw;
- Throws a different exception and provides richer exception information to the code at the higher layer of the Call Stack, that is, throw ex; // here, ex is a 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 register with the FirstChanceException event of AppDomain, so that as long as the AppDomain encounters an exception, it will receive a notification and will call these Event Callback functions before the CLR starts to search for any catch Block.
- Finally block
- Finally block is the code that will be executed.
- If an exception is thrown inside catch and finally, the exception in try will not be recorded and its information will be lost.
System. Exception class
Microsoft requires that all CLS-compatible programming languages must throw and catch exceptions derived from this type.
In general, this class also has three attributes:
- Message indicates the cause of the exception.
- InnerException if the current exception is thrown when processing an exception, the InnerException is the previous exception. The public method GetBaseException can be used to traverse the internal exception linked list and return the initial exception.
- StackTrace contains the names and signatures of all methods called before an exception is thrown. It returns a method that captures unknown information from the position where the exception is thrown.
Throw an exception
Two issues need to be considered when throwing an exception:
The first is the Exception type thrown. Select a more meaningful type. Consider the code at the top of the call stack, and know how the code judges a method failure to execute a proper recovery code. The author strongly recommends that the exceptional inheritance hierarchy be light and wide, so that you can create as few base classes as possible. The base class means to handle many errors as one.
The second is the string message that is passed to the constructor of the exception type.
Custom exception class
It seems that the custom Exception class is very simple. You only need to inherit the System. Exception class and it will be OK. However, this is actually a very tedious task.
Because all classes derived from the System. Exception class should be serializable so that they can write logs or databases through the AppDomain boundary. Serialization involves many problems.
The author wrote a generic exception class to simplify it. I will not write it here. In fact, just find a system exception in the format and write it as follows:
Do not forget to add the [Serializable] feature to the custom class.
The author's method is more advanced. he builds a generic Exception class to inherit Exception, and then writes some constructor or serialization functions into this class. The personalized exception information is used as the generic variable T and transmitted to the generic exception class to simplify the process.
------ To be continued, the above is still the foundation, and then I will write how to correctly use the Exception Handling Mechanism ---------
Exchange reliability for development efficiency
Design specifications and best practices
Unprocessed exceptions
Debug exceptions
Performance issues of Exception Handling
Restricted execution Area
Code Protocol