In-depth study of "abnormal mechanism" in Java

zhaozj2021-02-16  109

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.

First, "anomaly class" organizational form

The exceptions generated by the method in the Java system class are organized into "exception classes, not in this paper discussions), this method and its related" exception class "is associated with the THROWS keyword, and these classes Both 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 checking data, when> 0 is considered legal, return legal values, * Otherwise, it is not legal, thrown "exception". * / ISLEGAL (INT DT) THROWS LOWZEROEXCEPTION / / This definition is called method and "exception" pass {// over ThROWS established associated IF (DT> = 0) {Return Data;} else throw new lowzeroException () / * Self-written anomaly class, inherited from exception * / class lowzeroException Exception Exception {public lowzeroException () {super ();}} Carefully observation method islegal (), it is the most worthy of the most important feature It has two ways of function outlet, one is an instance of the method itself defined by the RETURN statement, and the other is the object instance of "exception classes", and Java To throw "abnormal". Compare how the same problem is dealt with:

INT ISLEGAL (INT DT) {if (DT> = 0) {RETURN DATA;} Else Return -1; // Indicates error}

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, the processing of "abnormal"

Java is processed by Try ... catch syntax to process "exception", which will associate with "exception classes" in the try {} block, cative () {} keywords can use meticulum, used for and method "" Anomaly target combined. 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" and This exception object has completed the combination, and then enters the Catch module to run. Specific process examples:

Example 2: / * Method to associate an abnormality included in the TRY module * / int mymethod (int DTA = 0; try {int data = islegal (} catch (lowzeroExcection 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 = ISLEGAL (DT); // References to the islegal () method here, 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 results of E.PrintStackTrace () are printed will be:

LowzeroException: At Example.islegal at Example Mymethod At Example.Mymethod2 At Example Main

From the previous result, we can see that from the LowzeroException "exception" generated, that is, contains the throw new lowzeroException (); the clause method begins, and then traces the way to generate the current thread (note: PrintStackTrace () is not traced back The capture point ends, but to the end of the method that produces the current thread). "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. Fourth, the need to pay attention to using the "unusual mechanism"

A variety of different exceptions may be generated in a method, you can set multiple "exception" throws to solve this problem. After the "abnormal" object is generated from the generated point, it is actually a passage-in process, so you can detect "exception" as needed to detect "exception" as needed. For example, in Example 3, if you don't need to know the specific generation of LowzeroException, you can use the "exception" public parent class Exception to combine "exception" object, ie catch (Exception E) {...}. Also in the delivery process associated with the "exception" and method, it is also possible to control the particle size of the associated "abnormality" as needed, that is, the parent class name of the abnormal object is kept behind. There is also a special situation in the "abnormal mechanism" --RuntimeException "exception class" (see Figure 1), this "exception class" and all its subclasses have a feature, which is "exception" object is generated by Java virtual The machine is processed directly, that is, the place where the throw clause appears in the method is captured by the virtual machine. Therefore, when throwing this "running abnormality" method is quoted, there is no need to have a try ... catch statement to handle "exception".

转载请注明原文地址:https://www.9cbs.com/read-14009.html

New Post(0)