Java exception mechanism and java Mechanism
The Exception mechanism in java is very important, and the program will inevitably encounter errors. The Exception mechanism can capture errors in the program to improve the stability and robustness of the program.
Exceptions in java are divided into Checked Exception (non-Runtime Exception) and UnChecked Exception (Runtime Exception). All Exception classes inherit Exception directly or indirectly. The Exception directly inherits from the Throwable class. The direct subclass of the Throwable class also has the error class. However, when an error occurs, the program will exit and cannot handle the error, so here we will focus on Exception classes. The RuntimeException class inherits from Exception, and the runtime exceptions directly or indirectly inherit from the RuntimeException class. Other non-runtime exceptions that inherit the Exception class can be found during compilation. A running exception occurs only during running. For example, if the arithmetic division is zero, it can be passed during compilation. However, an exception is thrown during running, and the divisor cannot be zero.
Java has two exception handling methods:
1. Capture exceptions
The structure is as follows:
1 try 2 3 {4 5 // Code 6 7} 8 9 catch (RuntimeException e) that may cause exceptions during execution) 10 11 {12 13 // handle caught exceptions 14 15} 16 17 catch (Exception e) // you can define the code to be executed after capturing multiple exceptions 18 19 {20 21 // process the caught exceptions 22} 23 24 finally25 26 {27 28, optional or optional. If yes, it will be executed, regardless of whether there are exceptions 29 30}Try-catch-finally
If an exception is caught, the following catch statements will not be executed, but if there is finally, the statements in the finally block will be executed.
2. The declaration throws an exception
Declare throws Exception in the method declaration where the method that generates an Exception is called. This method will not handle this type of Exception, but will be handled by the caller of this method.
3. Manually throw an exception
Throw an exception directly in the method. throw exception;
We recommend that you do not handle exceptions during running.
A custom Exception is a subclass that inherits from the Exception class. Generally, it does not inherit from the RuntimeException class. If a return statement exists in the try block, if a finally BLOCK statement exists, then you must execute the finally BLOCK statement before returning it. However, if the try block contains System. the exit (0) statement does not execute the finally BLOCK statement, because System. exit (0) terminates the currently running Java virtual machine, and the program ends before the termination of the virtual machine.
1 class myException extends Exception2 {3 public myException (String str) 4 {5 super (str); 6} 7}MyException
Exceptions can be used in File Processing and input/output stream applications.
Common exception types include:
1. java. lang. NullPointerException: a null pointer exception occurs because a reference is null, but a referenced method is called in the program.
2. java. lang. ClassNotFoundException: the specified class cannot be found. It may be that the class is not defined.
3. java. lang. ArithmeticException: an arithmetic exception. For example, the divisor is zero.
4. FileNotFoundException: the specified file cannot be found during file processing.
5. IOException: the input/output stream is abnormal.
6. SQLException: SQL exception. An error occurs when an SQL statement is executed.
There are also many types of exceptions that will be encountered in future programming.
What is the role of the exception mechanism in Java?
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 LowZero ...... remaining full text>
What is the java exception mechanism?
When a JAVA program violates the JAVA Semantic Rules, the JAVA Virtual Machine will indicate an error as an exception. Violation of Semantic Rules includes two situations
. One is the built-in semantic check of the JAVA class library. For example, if the array subscript is out of the range, IndexOutOfBoundsException is triggered.
NullPointerException is thrown. Another scenario is that JAVA allows programmers to extend this semantic check. programmers can create their own exceptions,
And freely choose when to use the throw keyword to cause an exception. All exceptions are subclasses of java. lang. Thowable.