Since this paper aims to explore the deep principles of the Java "abnormal mechanism", the use of "abnormal" is not described in detail. First see a very familiar C block used to open a file:
File * fp;
FP = FOPEN (FileName, "RW");
IF (fp == NULL) {
Printf ("Cannot Open File / N);
exit (0);
}
In this program, a paragraph in the IF condition statement is used to handle the specified file, or other reasons cannot open the specified file correctly. However, if you encounter a programmer that is responsible, he may think that there is a small possibility of finding a file, or forgetting this situation because the idea is concentrated in the implementation of the program function. The program can also be compiled correctly, and there will be no problems in general. However, this program can be sure to say that it is not strong enough, and once this program has a mistake, it will make the programmer to find the error. There are many examples in C language and most other advanced languages. That is, when a function is in use, there may be a case where the purpose of the use of this function may have, even if this abnormal situation occurs in this specific use environment, only one is one-thousand. The commonly used method is that programmers must fully understand how the probability that the function may not be able to execute correctly, and then add the corresponding conditional judgment statement to perform processing. There will be an example of this problem later. The "abnormal mechanism" of Java is to deal with the above problems very simple and flexible way. In general, other advanced languages are mainly to let function users pay attention to the exceptions that may occur, while Java is intended to give this matter to methods (and functions corresponding to function, in Java said in Java.) Come. This will not be due to the user's user, or if the responsibility is not strong, or if the work is lost, it will forget to handle the abnormal conditions that may occur during use. What is troublesome is that when using a method that may have an abnormal method, it must not be considered, but must do corresponding processing. That is to say, if I have forgotten the IF block, this program can even have a foreign line boss, but when using Java to complete this feature, as long as the method used the "exception" mechanism, If the method that may generate an "abnormal" method is not processed, the Java compiler does not pass it. I. The anomalies generated by the method of "anomaly class" Java system classes are organized into "exception classes" (there are Error classes, not in this article discussions), this method and its related "exception class" through throws The keyword is associated, and these classes must be subclasses of the Exception class. In any way they develop, if some exception can be generated, this exception can be organized into an "exception class", but this "exception class" must also be subclats of Exception, or grandson, etc. . example 1:
/ * Islegal is legal in the inspection data, and when> 0 is considered legal, return legal value,
* Otherwise, it is not legal, throwing "abnormal". * /
INT ISLEGAL (INT DT) THROWS LOWZEROEXCEPTION / / This definition is called method and "exception"
{// over THROWS has been associated
IF (dt> = 0) {
Return Data;
}
Else
Throw new lowzeroException ();
}
/ * Self-written anomaly, inherit from Exception * / Class LowzeroException Extends Exception
{
Public lowzeroException () {
Super ();
}
}
Careful observation method islegal (), it is the most worthless feature of it, it has two ways of function outlet, one is an instance of the type itself defined by the RETURN statement, the other is through Throw, returning is an object instance of "exception class", and Java is called "exception". Compare how the same problem is dealt with:
INT islegal (int dt) {
IF (dt> = 0) {
Return Data;
}
Else
Return -1; // indicates an error through a specific value
}
Since c can only return a function value by Return, it may be processed in the above manner when processing an abnormality. Of course, this requires the user of the islegal () function must know that the use of return value -1 in the function indicates that the unlaminated data. Comparing these two processing methods, you can know that Java's "abnormal mechanism" puts the functions of processing exception events. It is separated by two different exports. All of these "exception classes" are uniformly organized into a tree tree. The "abnormal mechanism" is like the logistics socialization of colleges and universities. The school's teaching function and school's logistics support are separated by logistics socialization, and the organizational form of the logistics group is independent of the school main body. It turns out that this organization not only improves service efficiency, but also improves service quality. The "Abnormal" organization of the entire Java system is shown in Figure 1:
In Example 1 ISLEGAL () method If there is no normal return number during the call, "exception" object is generated in the "exception" generating point, then this "exception" object is received by anyone, and handles it ? Let's answer this question. Second, "Abnormal" processing process Java is processed by Try ... catch syntax by Try ... Catch syntax, which will be associated with "exception classes" in the try {} block, cative () {} keyword can be used Combination of an "abnormality" object generated by the method. When a method is called, the conditions that cause an exception event occurred, and the "exception" will throw "exception", the original program process will be interrupted at this method, and then the TRY module is followed by "Conversion" in the CATCH and This exception object has completed the combination, and then enters the Catch module to run. Specific process example Example: Example 2:
/ * The method of abnormal association is included in the TRY module * /
INT mymethod (int dt) {
INT DATA = 0;
Try {
INT DATA = islegal (DT);
} catch (lowzeroexception e) {
System.out.println ("Data Error!");
}
Return Data;
}
Third, "Abnormal" processing method There are two ways to process "abnormal": the first as described in Example 2, the method containing "abnormal" outlet directly in the TRY block, and then captured by the following Catch block. The second is that it is not directly listened to the "exception" of the reference method, but transmit this "exception" association to the reference method, while listening to the capture work is also transmitted upward. Example 3:
INT MyMethod2 (int DT)
{
INT DATA = 0;
Try {
Data = MyMethod (DT)
} catch (lowzeroexception e) {
System.out.println ("Data Error!");
E.PrintStackTrace ();
}
Return Data;
}
Int Mymethod (int DT) THROWS LOWZEROEXCEPTION
{
INT DATA = ISLGAL (DT); // References here to the islegal () method, but does not capture its "exception"
Return Data;
}
From the above example, you can see that the "exception" LowZeroException generated by the method ISLEGAL () it references is created, that is, completed the upward transfer of "exception", at this time myMethod () method body Although there is only one Return return statement, but it actually has a function exit of two ways, one is a shaping value returned by return, the other is the "exception class" referred to in the THROWS key in the method name. "Example object. Correspondingly, the work of listening capture is handed over to the previous layer method mymethod2 (). The same truth, MyMethod2 () can also transfer "exception" through the association of ThROWS. In this case, once an "exception" is captured, this "exception" must have a pass path, and if we join the PrintStackTrace () method in the capture point Catch block, you can clearly see this "exception". How is it passed? For example, in Example 3 If "exception" is captured, the result of E.PrintStackTrace () is: LowzeroException: At Example.islegal at Example Mymethod at Example.Mymethod2 At Example Main From the previous result we can see, From the LowzeroException "exception", it is included with the throw new lowzeroException (); the clause method begins, and then traces the way to generate the current thread (Note: PrintStackTrace () is not traced back to the capture point, but to generate the current The method of thread ends). "Abnormal" generated LowzeroException "exception" object, first assigned to ISLGAL () associated LowzeroException class's unknown reference, then continue to assign a nameless reference to the LowzeroException class associated with MyMethod (), then continue to assign myMethod2 ( The meticulum elements in the CATCH block, finally being processed here, this "abnormal" object disappears. It can be said that catch () {} is the endpoint of the "exception" object. Also note that the correlation between the method and "exception" can be transferred up, and when it is passed to the main association, it is used in the main main () method, at this time, there is no other method of the virtual machine. Quote the main () method, and the try ... catch block may not be seen in the program, but no errors are generated, because the virtual opportunity captures "exception", and will default to call the printstacktrace () method Print "exception "path. In summary, as long as a method is associated with "exception", this "exception" can be transmitted upward, but it will eventually use Catch to terminate "exception", or transferred to the main () method to the Java virtual machine to end the "exception" object. Life, otherwise it is not compiled. 4. Some points to pay attention to using the "exception mechanism" 1. A number of different exceptions may be generated, you can set multiple "exception" throws to solve this problem.