Java Exception Handling Summary
Exception Handling is a very important aspect in programming and a major difficulty in programming. From C, you may already know how to use if... else... to control exceptions, it may be spontaneous. However, this kind of control exception is painful. If the same exception or error occurs in multiple places, you must perform the same processing in each place, it's quite troublesome! At the beginning of its design, the Java language considered these issues and proposed a framework scheme for exception handling. All exceptions can be represented by one type, different types of exceptions correspond to different sub-class exceptions (here the exception includes the error concept), defines the exception handling specifications, and adds the exception chain mechanism after version 1.4 to facilitate exception tracking! This is the skill of the Java language designer and also a difficult point in the Java language. The following is a summary of my knowledge about Java exceptions, which is also a collection of resources.
I. Basic knowledge about Java exceptionsExceptions are some errors in the program, but not all errors are exceptions, and sometimes they can be avoided. For example, if your code is missing a semicolon, the running result indicates that the error occurs in java. lang. error; if you use System. out. println (11/0), so you do the divisor with 0, will throw java. lang. arithmeticException. Some exceptions need to be processed, while others do not need to be captured and processed. The sky is unpredictable, and everyone is lucky, as are Java program code. In the programming process, we should first avoid errors and exceptions as much as possible. For unavoidable and unpredictable situations, we should consider how to handle exceptions. Exceptions in Java are represented by objects. Java processes exceptions by exception type. Different exceptions are classified by type. Each exception corresponds to a class, and each exception corresponds to an exception (class) object. Where does the exception class come from? There are two sources: one is some basic Exception types defined by the Java language itself, and the other is exceptions defined by the user by inheriting the Exception class or its subclass. The Exception class and its subclass are a form of Throwable, which specifies the conditions that a reasonable application wants to capture. Where can an exception object come from? There are two sources: one is that the Java Runtime Environment automatically throws the exception generated by the system, regardless of whether you are willing to capture and process it, it will always be thrown! For example, an exception occurs when the divisor is 0. The second is an exception thrown by the programmer. This exception can be defined by the programmer or defined in the Java language. An exception is thrown using the throw keyword, this exception is often used to report abnormal information to the caller. Exceptions are for methods. Throws, declaration throws, captures, and handles exceptions in methods. Java exception handling is managed by five keywords: try, catch, throw, throws, and finally. The basic process is to use the try statement block to wrap the statement to be monitored. If an exception occurs in the try statement block, the exception will be thrown, your code can capture and handle this exception in the catch statement block, and some system-generated exceptions are automatically thrown during Java runtime. You can also declare the method to throw an exception through the throws keyword, and then throw an exception object through throw in the method. The finally statement block is executed before the return method is executed. The general structure is as follows:
Try {
Program code
} Catch (exception type 1: Abnormal variable name 1 ){
Program code
} Catch (exception type 2: Abnormal variable name 2 ){
Program code
} Finally {
Program code
} Multiple catch statements can be used to match multiple exceptions. After matching one of the above statements, only matching exceptions are executed when the catch statement block is executed. The catch type is defined in the Java language or defined by the programmer. It indicates the type of the Code that throws an exception, and the variable name of the exception indicates the reference of the object that throws the exception, if catch captures and matches the exception, you can directly use the exception variable name. At this time, the exception variable name points to the matched exception and can be referenced directly in the catch code block. This is very special and important! The purpose of Java exception handling is to improve program robustness. You can give the program a correction opportunity in catch and finally code blocks so that the program does not terminate due to exceptions or changes other than the process. At the same time, it provides convenience for program development and maintenance by obtaining Java exception information. Generally, the exception information can be used to quickly locate the problem (CODE. Java exception handling is a major feature and difficulty of the Java language. Mastering exception handling can make the written code more robust and easy to maintain.
Ii. Java exception class diagramThe following is a Hierarchy Diagram of these classes:
Java. lang. Object
Java. lang. Throwable
Java. lang. Exception
Java. lang. RuntimeException
Java. lang. Error
The following four classes of java. lang. ThreadDeath are introduced from the java api documentation. 1. Throwable
The Throwable class is a superclass of all errors or exceptions in the Java language. Only when an object is an instance of this type (or its subclass) can it be thrown through a Java virtual machine or Java throw statement. Similarly, only this class or its subclass can be the parameter type in the catch clause. Two subclass instances, Error and Exception, are usually used to indicate exceptions. Generally, these instances are newly created in the context of an exception and contain relevant information (such as stack trace data ). 2. Exception
The Exception class and its subclass are a form of Throwable. It specifies the conditions that a reasonable application wants to capture, indicating the exceptions that the program itself can handle. 3. Error
An Error is a subclass of Throwable, indicating a serious Error that cannot be recovered by the program itself. It is used to indicate that a reasonable application should not try to capture a serious problem. During the execution of this method, you do not need to declare any subclass of an Error that may be thrown but not captured through throws in the method, because the Java compiler does not check it, that is, when such exceptions may occur in the program, even if try... catch statements capture it, and throws statements are not used to declare whether to throw it or compile it. 4. RuntimeException
RuntimeException is a super class that may throw exceptions during the normal operation of the Java Virtual Machine. The Java compiler does not check it, that is, when such exceptions may occur in the program, even if try... catch statements capture it, and throws statements are not used to declare whether to throw it or compile it. This exception can be avoided by improving code implementation. 5. ThreadDeath
When the stop method with zero parameters in the Thread class is called, the affected Thread will throw a ThreadDeath instance. The instance of this class should be captured only when the application must be cleared after the asynchronous termination. If ThreadDeath is captured by a method, it is very important to throw it again, because in this way, the thread can be truly terminated. If ThreadDeath is not captured, the top-level error handler does not output messages. Although the ThreadDeath class is "normal", it can only be a subclass of Error rather than an Exception, because many applications capture all exceptions and then discard them. The above is a brief introduction to abnormal APIs. The usage is very simple. The key is to understand the principle of exception handling. For detailed usage, see the Java API documentation.
Iii. Java Exception Handling MechanismThere are two solutions to code that may encounter exceptions:
First, use the try... catch statement in the method to capture and handle exceptions. catach statements can have multiple to match multiple exceptions.For example:
Public void p (int x ){
Try {
...
} Catch (Exception e ){
...
} Finally {
...
}
}
Second, for exceptions that cannot be processed or exceptions that require transformation, throw an exception through the throws statement in the method declaration.Example: public void test1 () throws MyException {
...
If (....){
Throw new MyException ();
}
} If an exception is thrown for each method, the Java Virtual Machine will look back from the abnormal code block in the multi-layer nested call of the method calling method, until the code block that handles the exception is found. Then, the exception is handed over to the corresponding catch statement for processing. If the Java Virtual Machine traces back to the main () method at the bottom of the method call stack, if the code block for exception handling is still not found, it will follow the steps below:
1. Call the printStackTrace () method of the abnormal object and print the exception information of the method call stack.
2. If an exception occurs to the main thread, the entire program is terminated. If the thread is not the main thread, it is terminated and other threads continue to run. Through analysis, we can see that the earlier the resource and time consumed by handling exceptions, the smaller the scope of impact. Therefore, do not send the exceptions that you can handle to the caller. Another point is that finally statements must execute code in any situation, which ensures the reliability of code that must be executed in any situation. For example, the JDBC connection should be released when the database query is abnormal. The finally statement is executed before the return statement, regardless of its location or whether the try block has an exception. The only case where the finally statement is not executed is that the System. exit () method is executed. System. exit () is used to terminate the currently running Java virtual machine. In the finally statement block, the return value cannot be changed by assigning a new value to the variable. We also recommend that you do not use the return statement in the finally block, which is meaningless and may cause errors. Finally, pay attention to the syntax rules for exception handling:
1. try statements cannot exist independently. They can be used with catch and finally to form try... catch... finally, try... catch, try... three finally structures: one or more catch statements and one finally statement. The three keywords try, catch, and finally cannot be used separately. Second, the variables in the try, catch, and finally code blocks are independent of each other and cannot access each other. If you want to access all three blocks, you need to define the variables outside these blocks. Third, when multiple catch blocks match one exception class or its subclass, the Java virtual machine executes the catch Block instead of other catch blocks. Fourth, throw statements cannot be followed by other statements because they are not executed. Fifth, if a method calls another method that declares to throw an exception, the method either handles the exception or declares to throw the exception. So how can we determine whether a method may be abnormal? In general, the throws statement is used in the method declaration. The method contains the throw statement, and the method declaration of the method call contains the throws keyword. Difference between throw and throws keywords
Throw is used to throw an exception in the method body. Syntax format: throw exception object.
Throws is used to declare what exceptions A method may throw. After the method name, the syntax format is: throws exception Type 1, exception type 2... exception type n.
4. How to define and use exception classes
1. Use existing exception classes, for example, IOException and SQLException. Try {
Program code
} Catch (IOException ioe ){
Program code
} Catch (SQLException sqle ){
Program code
} Finally {
Program code
} 2. custom exception classes
Create an Exception or RuntimeException subclass to obtain a custom Exception class. For example:
Public class MyException extends Exception {
Public MyException (){}
Public MyException (String smg ){
Super (smg );
}
} 3. Custom exceptions
The throws declaration method may throw a custom exception and throw a custom exception in the appropriate place with the throw statement. For example, an exception is thrown in a condition.
Public void test1 () throws MyException {
...
If (....){
Throw new MyException ();
}
} Exception Transformation (also called translation) makes exceptions easier to read and understand
Public void test2 () throws MyException {
...
Try {
...
} Catch (SQLException e ){
...
Throw new MyException ();
}
}
Another code is very interesting: Public void test2 () throws MyException { ... Try { ... } Catch (MyException e ){ Throw e; } } This piece of code actually captures the exception, and then shares it with the disk. It doesn't make sense. If there is anything better to handle it, just don't handle it. Simply throws the Code directly before the method. Exception capture requires some meaningful processing.
5. runtime exceptions and checked exceptions There are two types of exceptions: runtime exceptions and checked exceptions.
1. runtime exception
RuntimeException class and its subclass are called runtime exceptions. This exception is characteristic of the Java compiler not checking it. That is to say, when such exceptions may occur in the program, even if try... catch statements capture it, and throws statements are not used to declare whether to throw it or compile it. For example, if the divisor is zero, a java. lang. ArithmeticException exception is thrown. 2. Check for exceptions
Except for the RuntimeException class and its subclass, all other Exception classes and their subclasses belong to the checked exceptions. This Exception is characterized by either try... catch capture and processing, or throws with throws statement declaration, otherwise the compilation will not pass. 3. Differences between the two
An exception during running indicates that the program cannot be resumed. The cause of this exception is generally due to an incorrect operation. Once an error occurs, we recommend that you terminate the program.
Checked exceptions indicate exceptions that can be processed by the program. If the method that throws an exception does not process it or cannot process it, the caller of the method must handle the exception. Otherwise, the call will fail and compilation will fail. Of course, these two exceptions can be captured and handled by a program. For example, if the divisor is zero, the runtime exception is: public class HelloWorld {
Public static void main (String [] args ){
System. out. println ("Hello World !!! ");
Try {
System. out. println (1/0 );
} Catch (ArithmeticException e ){
System. out. println ("division is 0! ");
}
System. out. println ("the program has not been terminated after the division is zero. Thank you !!! ");
}
} Running result:
Hello World !!! The divisor is 0! The program has not been terminated after the division is zero !!!4. runtime error
The Error class and its subclass indicate runtime errors, which are usually thrown by the Java Virtual Machine. Some Error classes are defined in JDK, such as VirtualMachineError.
And OutOfMemoryError, which cannot be fixed by the program itself. Generally, the Error class is not extended to create custom Error classes. The RuntimeException class indicates errors in the program code, which can be extended. You can create exception classes at specific runtime.
Errors (runtime errors) and runtime exceptions are the same: the Java compiler does not check them and stops running when they occur during the program running. 5. Best Solution
For runtime exceptions, do not use try... catch is used to capture and handle the exception. In the program development and debugging stage, try to avoid this exception. Once this exception is found, the correct method will improve the Code and implementation method of the program design, modify errors in the program to avoid such exceptions. Capturing and handling runtime exceptions is a good solution, because you can avoid this exception by improving the code implementation.
For checked exceptions, if they are not mentioned, they will be handled in a down-to-earth manner, either captured and resolved using try... catch or throws!
For errors (runtime errors), you do not need to perform any processing in the program. When a problem occurs, you should locate the problem outside the program and solve it.
Vi. Abnormal transformation and exception chainException transformation has already been mentioned above. In fact, after an exception is caught, the exception is thrown again with a new type. This is generally more intuitive for the exception information! For example:
Public void run () throws MyException {
...
Try {
...
} Catch (IOException e ){
...
Throw new MyException ();
} Finally {
...
}
}
Exception chainIn JDK1.4 and later versions, the Throwable class supports the exception chain mechanism. Throwable contains a snapshot of the thread execution stack when its thread is created. It also contains a message string that provides more information about the error. Finally, it can also contain cause: Another throwable that causes this throwable to throw. It is also called an exception chain facility, because cause itself also has cause, and so on, it forms an exception chain, and every exception is caused by another exception.
In general, the exception chain encapsulates the original exception as a new exception class and encapsulates the original exception class in the new exception class, the purpose is to find the root cause of the exception.
Two Throwable constructor methods can be used to create a custom exception type that contains the exception cause:
Throwable (String message, Throwable cause)
Construct a new throwable with the specified detailed message and cause.
Throwable (Throwable cause)
Construct a string with the specified cause and (cause = null? Null: New throwable for detailed messages of cause. toString () (which usually contains detailed messages of classes and cause.
GetCause ()
Return the cause of the throwable. If the cause does not exist or is unknown, null is returned.
InitCause (Throwable cause)
Initialize the cause of throwable to a specified value.
In the Exception subclass of Throwable, there is a similar constructor for specifying the Exception cause:
Exception (String message, Throwable cause)
Creates a new exception with the specified detailed message and cause.
Exception (Throwable cause)
According to the specified reason and (cause = null? Null: detailed message of cause. toString () constructs a new exception (it usually contains the cause class and detailed message ).
Therefore, you can extend the Exception class to construct a new Exception class with the Exception cause.
7. Java Exception Handling principles and skills
1. Avoid too large try blocks. Do not place codes that do not encounter exceptions in try blocks. try to keep one or more exceptions corresponding to one try block.
2. Refine the exception type. Do not write Excetpion whatever type of exception.
3. Try to keep a catch exception for a block. Do not ignore the caught exception. After capturing the exception, either process it, translate it, or throw a new type of exception.
4. Do not throw exceptions that you can handle to others.
5. Do not use try... catch to control the program process. The fundamental purpose of exception Control is to handle abnormal conditions of the program.
References I mainly use Java API documentation (version 1.5), books I have read, and other scattered materials. Major e-books include:
Java2 reference
Thinking in Java
Java core technology (Volume 1)
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.