JAVA basics: an in-depth study of "exception mechanism" in Java
Source: Internet
Author: User
JAVA basics: & quot; Exception Mechanism & quot; in Java in-depth study-Linux general technology-Linux programming and kernel information. The following is a detailed description. This article aims to explore the deep principles of Java "exception mechanism", so the usage of "exception" is not described in detail. First, let's look at a very familiar section of C program 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 section in the if Condition Statement is used to process the specified file that is not found, or the specified file cannot be correctly opened for other reasons. However, if a programmer has a weak sense of responsibility, he may think that it is very unlikely that the file cannot be found, or he forgot to handle this situation due to the idea of focusing on the implementation of program functions. At this time, the program can also be correctly compiled, and generally there will be no problems. But at this time, this program is definitely not robust enough, and once the program has an error, it will make it difficult for programmers to find out where the error is. There are many examples of this in C language and most other advanced languages.
That is, when a function is used, it may not be used, even in the specific use environment of this program, this exception may only happen in one thousandth. A common solution is that when a programmer needs to use a function, he must fully understand the possible causes for the function to fail to be correctly executed, and then add the corresponding condition judgment statement for processing. Here is an example to illustrate this problem.
Java's "exception mechanism" is a simple and flexible way for programmers to solve the above problems. In general, other advanced languages mainly enable function users to pay attention to the exceptions that may occur in the function, while java gives this thing to the method (the concept corresponding to the function, in Java. This makes it easier for the method user to avoid being less responsible or losing three things, forgetting to handle possible exceptions when using the method. The trouble is that when using a method that may cause exceptions, you cannot turn a blind eye to it and must handle it accordingly. That is to say, if you forget the if block in the above C section, this program can even be used by a layman, but when Java is used to complete this function, as long as the method used uses the "exception" mechanism, if the method that may generate "exception" is not processed accordingly, the java compiler will not let it pass.
I. organization form of "exception type"
Exceptions generated by methods in the Java System class are organized into "exception classes" (there are also Error classes, which are not covered in this article ), this method is associated with its related "Exception class" through the throws keyword, and these classes must be subclasses of the Exception class. If an exception may occur in any self-developed class method, you can also organize this exception into an "exception class ", however, this "Exception class" must also be a subclass of Exception, or a grandson class.
Example 1:
/* IsLegal checks whether the data is valid. If the value is greater than 0, it is regarded as valid. A valid value is returned,
* Otherwise, an "exception" is thrown ". */
Int isLegal (int dt) throws LowZeroException // This definition is referred to in this document as the method and "exception"
{// Throws establish Association
If (dt> = 0 ){
Return data;
}
Else
Throw new LowZeroException ();
}
/* Self-written Exception classes inherited from Exception */
Class LowZeroException extends Exception
{
Public LowZeroException (){
Super ();
}
}
Take a closer look at the isLegal () method. The most noteworthy feature is that it has two function exits, one is through the return statement, an instance of the type defined by the method itself is returned, and an object instance of the "exception class" is returned through throw. in Java, an "exception" is thrown ". Compare how to solve the same problem in C:
Int isLegal (int dt ){
If (dt> = 0 ){
Return data;
}
Else
Return-1; // an error is indicated by a specific value.
}
Since C can only return function values through return, the above methods may be used to handle exceptions. Of course, this requires that the isLegal () function user must know that the function uses the return value-1 to indicate that the data is invalid.
By comparing the two methods, we can know that java's "exception mechanism" separates the functions of handling exception events from the functions of the method itself through two different outlets.
All these "exception classes" are organized into a class tree independently of the Methods of specific services. The "exception mechanism" is like the socialization of Logistics in colleges and universities. the socialization of logistics separates the teaching functions of schools from the logistics support of schools, in addition, the organizational structure of the logistics group is independent of the school. Facts have proved that this organization not only improves service efficiency, but also improves service quality. As shown in organization 1 of the "exception class" in the Java System:
(400) {this. resized = true; this. width = 400; this. alt = 'click here to open new window';} "onmouseover =" if (this. resized) this. style. cursor = 'hand'; "onclick =" window. open ('HTTP: // java.ccidnet.com/col/attachment/2006/8/802851.gif'); ">
If the isLegal () method in Example 1 does not return an integer during the call, an "exception" object is generated at the "exception" occurrence point, who will receive this "exception" object and process it? Here is the answer to this question.
Ii. Handling of "exceptions"
In Java, try... The catch syntax is used to handle "exceptions". methods associated with "exception classes" are included in the try {} block. The catch () {} keyword can use the form parameter, used to combine with the "exception" object generated by the method. When a method is called and the condition that causes the exception event is true, an "exception" will be thrown, and the original program flow will be interrupted at this method, then, the "parameter" in the catch followed by the try module is combined with the exception object, and then runs in the catch module. Process example:
Example 2:
/* Include the associated methods with exceptions in the try module */
Int myMethod (int dt ){
Int data = 0;
Try {
Int data = isLegal (dt );
} Catch (LowZeroException e ){
System. out. println ("A data error occurred! ");
}
Return data;
}
Iii. troubleshooting of "exceptions"
There are two ways to handle "exception": Example 2: Put the method containing the "exception" exit directly into the try block, and then catch it by the catch Block that follows. The second is to pass the "exception" association to the reference method instead of directly capturing the "exception" of the referenced method, and the listening capture work is also passed up accordingly.
Example 3:
Int myMethod2 (int dt)
{
Int data = 0;
Try {
Data = myMethod (dt)
} Catch (LowZeroException e ){
System. out. println ("A data error occurred! ");
E. printStackTrace ();
}
Return data;
}
Int myMethod (int dt) throws LowZeroException
{
Int data = isLegal (dt); // The isLegal () method is referenced here, but its "exception" is not caught"
Return data;
}
From the above example, we can see that the method myMethod () is associated with the "exception" LowZeroException () produced by the method isLegal () It references, that is, it completes the upward transfer of the "exception" association, at this time, although there is only one return statement in the myMethod () method body, it actually has two function exits, one is the integer value returned by return, the other is to return the Instance Object of the "exception class" referred to by the throws keyword in the method name. Correspondingly, the monitoring and capturing work is handed over to the previous method myMethod2 (). Similarly, myMethod2 () can pass "exception" Through throws Association. In this case, once an "exception" is caught, this "exception" must have a transfer path. If we add the printStackTrace () method to the catch Block of the capture point, you can clearly see how this "exception" is passed. For example, in Example 3, if an "exception" is caught, the result printed by e. printStackTrace () is:
LowZeroException:
At Example. isLegal
At Example myMethod
At Example. myMethod2
At Example main
From the above results, we can see that the occurrence point of LowZeroException "exception", that is, the method containing throw new LowZeroException (); clause, starts from, and goes back to the method that generates the current thread (note: printStackTrace () is not traced back to the end of the capture point, but to the end of the method that generates the current thread ). The LowZeroException "exception" object generated by a vertex is first assigned to the unknown reference of the LowZeroException class associated with isLegal (), and then assigned to myMethod () the unknown reference of the associated LowZeroException class will be assigned to the form parameter e in the catch Block in myMethod2 (), and will be processed here. The "exception" object will disappear immediately. It can be said that catch () {} is the end point of the life of the "exception" object.
Note that the association between methods and "exceptions" can be passed up all the time. When it is passed to the association with the main method, throws Exception is used in the definition of the main () method, in this case, there are no other methods except virtual machines that can reference the main () method, and try… may not be seen in the program... Catch Block, but it does not produce errors, because the virtual opportunity captures "exception", and prints the "exception" path by default by calling the printStackTrace () method. In short, as long as a method is associated with an "exception", the "exception" association can be passed up, but the catch must be used to terminate the "exception", or always passed to main () the method is handed over to the Java Virtual Machine to end the life of the "exception" object. Otherwise, compilation will fail.
4. Notes for using the "exception mechanism"
1. Multiple exceptions may occur in a method. You can set multiple "exception" throws to solve this problem.
2. an "exception" object is a value transfer process from the time it is generated to the time it expires after it is captured. Therefore, you can, to control the granularity of "exceptions. For example, in Example 3, if you do not need to know that the LowZeroException "Exception" is generated, you can use the common parent Exception of "Exception" to combine the "Exception" object, that is, catch (Exception e ){...}. Similarly, in the transfer process of "exception" and Method Association, you can also control the granularity of association "exception" as needed, that is, throws follows the parent class name of the exception object.
3. Is there another special situation in "exception mechanism ?? RuntimeException "exception class" (see). This "exception class" and all its sub-classes have a feature, that is, when an "exception" object is generated, it is directly processed by the Java Virtual Machine, that is, the throw clause in the method is easily captured by the virtual machine. Therefore, when a method that throws this "RunTime exception" is referenced, try… is not required... Catch statement to handle "exceptions ".
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.