Exception Handling in Java
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 exceptions
Exceptions 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
}
There can be multiple catch statements to match multiple exceptions. After matching one of the above, only the 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 diagram
The following is a Hierarchy Diagram of these classes:
Java. Lang. Object
Java. Lang. throwable
Java. Lang. Exception
Java. Lang. runtimeexception
Java. Lang. Error
Java. Lang. threaddeath
The following four classes 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 Mechanism
There 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. For 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:
Throw an exception in a certain condition.
Public void test1 () throws myexception {
...
If (....){
Throw new myexception ();
}
}
Transforming exceptions (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, such as running exceptions with Zero Divisor:
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 chain
Exception 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 chain. In Versions later than jdk1.4, 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.