0. Why the exception handling mechanism should be introduced.
Before the exception mechanism is introduced, the exception is handled using If...else,sysout and Syserror methods. Exception handling is a very important aspect of program design, but also a great difficulty in programming, starting from C, you may already know how to use if...else ... To control the anomaly, perhaps spontaneously, but this control is extremely painful, the same exception or error if multiple places appear, then you have to do the same in every place, feel quite troublesome.
The Java language was designed to take into account these problems, proposed exception handling framework of the scheme, all of the exceptions can be expressed in a type, different types of exceptions corresponding to different subclass exceptions (where the exception includes the concept of error), the definition of exception handling specifications, The exception chain mechanism was added after version 1.4 to facilitate tracking of exceptions.
Program execution often occurs in addition to 0 overflow, array and other running errors, affecting the normal execution of the program. Errors and anomalies are unavoidable, a good application, in meeting the user requirements of the various functions, but also should be able to foresee the implementation of the program may produce various anomalies of the ability to "try", and for exceptional circumstances to give appropriate treatment "catch." In the Java language, this technique is exception handling
The Java language solves run-time errors through an object-oriented exception handling mechanism that prevents unexpected results from incorrect program code or system errors. Reduce the programmer's work, increase the flexibility of the program, increase the readability and robustness of the program.
The purpose of Java exception handling is to improve the robustness of the program, and you can give the program an opportunity to fix it in the catch and finally blocks of code so that the program is not terminated by the exception or changes that occur outside the process. At the same time, by obtaining the Java exception information, it is also convenient for the development and maintenance of the program, and it is common to find the abnormal problem (code) by the exception information.
Java exception handling is a major feature of the Java language, but also a difficult task, mastering exception handling can make the written code more robust and easy to maintain.
Basic knowledge of Java exceptions
Exceptions are errors in a program, but not all errors are exceptions, and errors can sometimes be avoided. For example, if your code is missing a semicolon, then the result is that the hint is error java.lang.Error; If you use System.out.println (11/0), then you're using 0 as a divisor, Throws a Java.lang.ArithmeticException exception. Some exceptions need to be handled, while others do not require capture processing, which is described in detail later. The sky is unpredictable, people have unforeseen, Java program code is also so.
In the process of programming, it is necessary to avoid errors and anomalies as far as possible, and how to deal with the unavoidable and unpredictable situations when considering the occurrence of anomalies. Exceptions in Java are represented by objects. The Java exception processing is handled by the exception classification, different exceptions have different classifications, each of which corresponds to a type (class), each exception corresponds to an exception (Class) object.
Where the exception class comes from. There are two sources, one is the basic exception type defined by the Java language itself, and the other is the exception that the user defines by inheriting the exception class or its subclasses. The Exception class and its subclasses are a form of throwable that indicates the conditions that a reasonable application wants to capture.
two. Where are the unusual objects coming from?
There are two sources, one is the Java Runtime Environment automatically throws system-generated exceptions, regardless of whether you are willing to capture and processing, it will always be thrown. Like an exception with a divisor of 0. The second is the exception that the programmer throws itself, this exception can be defined by the programmer itself, or it can be defined in the Java language and thrown with the throw keyword, which is often used to report some information about the exception to the caller.
Exceptions are for methods, and throwing, declaring, capturing, and handling exceptions are done in the method.
Java exception handling is managed through 5 keyword try, catch, throw, throws, finally. The basic procedure is to wrap the statement you want to monitor with a try statement block, and if an exception occurs inside a try statement block, the exception is thrown, and your code catches the exception in the catch statement block and handles it, and some of the system-generated exceptions are automatically thrown in the Java runtime. You can also declare the method to throw an exception by using the throws keyword, and then throw the exception object through throw inside the method. Finally statement blocks are executed before the method executes return, and the general structure is as follows:
try{
Program code
}catch (Exception type 1 exception variable name 1) {
Program code
}catch (Exception type 2 exception variable name 2) {
Program code
}finally{
Program code
}
how multiple catch statements are handled. a catch statement can have more than one exception that matches multiple exceptions, and when a catch statement block is executed, only the exception on the match is executed. The type of catch is defined in the Java language or defined by the programmer itself, representing the type of code that throws an exception, the variable name of the exception represents the reference to the object that threw the exception, and if the catch catches and matches the exception, the exception variable name can be used directly. The exception variable name points to the matching exception and can be referenced directly in the catch code block. This is very, very special and important.
Class diagram of Java exception class
The following is a hierarchical 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. An object can be thrown through either a Java virtual machine or a Java throw statement only if it is an instance of this class (or one of its subclasses). Similarly, only one of this class or its subclasses can be a parameter type in a catch clause.
Two instances of subclasses, Error and Exception, are typically used to indicate that an exception has occurred. Typically, these instances are newly created in the context of an exception, and therefore contain related information, such as stack trace data.
2, Exception
The Exception class and its subclasses are a form of throwable that indicates the conditions that a reasonable application wants to capture, representing the exceptions that the program itself can handle.
3. Error
Error is a subclass of Throwable that represents a serious error that cannot be recovered by the program itself, and is used to indicate a serious problem that a reasonable application should not attempt to catch.
During the execution of this method, it is not necessary to declare in the method any subclass of the Error that may be thrown but not captured, because the Java compiler does not check it, that is, when such an exception may occur in the program, even if it is not captured with the Try...catch statement, the Nor does it use the throws Word declaration to throw it, or it will compile through.
4, RuntimeException
RuntimeException are superclass of exceptions that may be thrown during the normal operation of a Java virtual machine. The Java compiler does not check it, that is, when such an exception may occur in a program, even if it is not captured with the Try...catch statement, it is not thrown with a throws clause declaration, or it is compiled through, and this exception can be avoided by improving the code implementation.
5, Threaddeath
When you call the Stop method with 0 arguments in the thread class, the victim thread throws a Threaddeath instance.
An instance of this class should be caught only if the application must clear after it has been terminated asynchronously. If Threaddeath is captured by a method, then it is important to throw it back because it will allow the thread to really terminate.
If Threaddeath is not captured, the top-level error handler does not output the message.
Although the Threaddeath class is "normal", it can only be a subclass of the Error, not a Exception subclass, because many applications capture all occurrences of Exception and then discard them.
The above is a simple introduction to the exception API, the usage is very simple, the key is to understand the principle of exception handling, the specific use of the Java API documentation.
Four, Java exception handling mechanism
There are two ways to handle code that might appear to be abnormal:
First, catch and handle exceptions in a method by using the Try...catch statement, which can have multiple occurrences to match multiple exceptions. For example:
public void P (int x) {
try{
...
}catch (Exception e) {
...
}finally{
...
}
}
Second, for exceptions that cannot be handled or to be transformed, an exception is thrown through the throws statement at the declaration of the method. For example:
public void Test1 () throws myexception{
...
if (...) {
throw new MyException ();
}
}
If each method is simply throwing an exception, in a multi-tiered nested call to the method invocation method, the Java virtual opportunity will look back from the method code block where the exception occurred, until the code block that handled the exception is found. The exception is then handed over to the appropriate catch statement for processing. If the Java Virtual Machine traces the main () method at the bottom of the method call stack, if the code block that handles the exception is still not found, the following steps are followed:
First, the Printstacktrace () method of the object that invokes the exception, printing the exception information for the method call stack.
Second, if the thread that has the exception is the primary, the entire program terminates, and if the thread is not the main, the other thread continues to run.
Through the analysis of thinking, we can see that the earlier processing of abnormal consumption of resources and time, the impact of the scope of the smaller. Therefore, do not throw the exception that you can handle to the caller.
It is also important not to overlook the code that must be executed in any case by a finally statement, which ensures that some of the code's reliability must be executed in any case. For example, when a database query is abnormal, you should release the JDBC connection, and so on. The finally statement executes before the return statement, regardless of its position, or whether an exception is found in a try block. Finally, the only thing that is not executed is that the method executes the System.exit () method. The role of System.exit () is to terminate the currently running Java virtual machine. Finally, it is not possible to change the return value by assigning a new value to a variable, and it is also recommended that you do not use returning statements in a finally block, which makes no sense and can easily lead to errors.
Five. Syntax rules for exception handling considerations
First, try statements can not exist alone, and catch, finally composed try...catch...finally, Try...catch, try...finally three of structures, catch statements can have one or more, Finally statements are up to one, try, catch, finally these three keywords can not be used alone.
Second, try, catch, finally three blocks in the scope of the variables are independent and cannot access each other. If you want to be accessible in three blocks, you need to define the variables outside the blocks.
Third, multiple catch blocks, when the Java Virtual Opportunity matches one of the exception classes or its subclasses, executes the catch block without executing another catch block.
Four, throw statements are not allowed to follow other statements, because these do not have the opportunity to execute.
If a method calls another method that declares an exception, the method either handles the exception or the declaration is thrown.
So how can you tell if a method might be abnormal? Generally speaking, the method declaration time uses the throws statement, the method has the throw statement, the method invocation method declaration has the throws keyword.
The difference between throw and throws keywords
Throw is used to throw an exception in the method body. The syntax format is: Throw exception object.
Throws is used to declare what exceptions the method might throw, after the method name, the syntax format is: throws exception type 1, exception type 2 ... Exception type N.
Vi. How to define and use exception classes
1, use the existing exception class, if for IOException, SQLException.
try{
Program code
}catch (IOException IoE) {
Program code
}catch (SQLException Sqle) {
Program code
}finally{
Program code
}
2.1 Why do you want to customize the exception class.
In actual development, developers often need to define exception classes to describe the exception information in their own programs to distinguish the exception information of other programs. You need to customize the exception class.
2.2 How to customize the Exception class.
The way to implement custom exception classes is as follows:
1. Class Java.lang.Throwable is the base class for all exception classes, which includes two subclasses: Exception and Error,exception classes are used to describe exceptions that a program can catch, such as classnotfoundexception. The error class is used to indicate a serious problem that a reasonable application should not attempt to catch, such as a virtual machine error virtualmachineerror
2, custom exception classes can inherit Throwable class or exception, rather than inherit the error class. There can also be inheritance relationships between custom exception classes
3, you need to design a construction method for the custom exception class to facilitate the construction of custom exception objects. Construction methods include: Exception (), Exception (String message), Exception (string message, Throwable cause), Exception (Throwable cause)
Create a exception or runtimeexception subclass to get a custom exception class. For example:
public class MyException extends exception{
Public myexception () {}
Public MyException (String SMG) {
Super (SMG);
}
}
3, use the custom exception
Declaring a method with throws can throw a custom exception and throw a custom exception in the appropriate place with the throw statement. For example:
Throw an exception in a condition
public void Test1 () throws myexception{
...
if (...) {
throw new MyException ();
}
}
Note: When a try block is followed by more than one catch block, if an exception occurs that matches the parameters of the first catch block, the exception handling rights are given to the first catch block, and if they do not match, the second catch block is matched, sequentially, If the exception is still not matched at the end, the method cannot handle the exception that occurred, and a throws statement is added to the method declaration to throw the exception. Therefore, in the case of multiple catch blocks, if there is an inheritance relationship between each of the exception types being processed, you should first catch the subclass exception and then catch the parent class exception
Transform the exception (also called translation), making the exception easier to read and easier to understand
public void Test2 () throws myexception{
...
try{
...
}catch (SQLException e) {
...
throw new MyException ();
}
}
There is also a code that is interesting:
public void Test2 () throws myexception{
...
try {
...
catch (MyException e) {
Throw e;
}
}
This code actually catches the exception, and then a clean, no point, if there is anything good to deal with, do not deal with the line, directly in the method before the throws declaration can be thrown. The catch of an exception will have to do some meaningful processing.
vii. run-time Exceptions and checked exceptions
Exception classes can be divided into two types: run-time exceptions and checked exceptions.
1. Run-time Exceptions
The RuntimeException class and its subclasses are known as Run-time exceptions, which are characterized by the Java compiler not checking it, which means that when such an exception is possible in a program, it is not captured with a Try...catch statement or thrown with a throws clause declaration , or it will compile through. For example, a Java.lang.ArithmeticException exception is thrown when the divisor is zero.
2. Abnormal check
In addition to the RuntimeException class and its subclasses, the other exception classes and their subclasses belong to the checked exception, which is characterized either by try...catch capture processing or by a throws statement declaration, otherwise the compilation will not pass.
3, the difference between the two
A Run-time exception represents an exception that cannot be restored by a program, and is usually caused by an incorrect action. Once an error occurs, it is recommended that the program be terminated.
A checked exception represents an exception that the program can handle. If the method that throws the exception itself does not handle or cannot handle it, then the caller of the method must handle the exception, otherwise the call will go wrong and the compilation cannot pass. Of course, both of these exceptions can be captured and processed by a program, such as a run-time exception with zero divisor:
public class HelloWorld {public
static void Main (string[] args) {
System.out.println ("HelloWorld!!!");
try{
System.out.println (1/0);
} catch (ArithmeticException e) {
System.out.println ("divisor is 0!");
}
System.out.println ("The divisor is zero after the program does not terminate AH, hehe!!!");
}
Run Result:
Hello World!!!
Divisor is 0!
The divisor is zero after the program does not terminate Ah, OH!!!
4. Run-time Error
The error class and its subclasses represent run-time errors, which are typically thrown by Java virtual machines, and the JDK defines some error classes, such as Virtualmachineerror and OutOfMemoryError, The program itself cannot fix these errors. Generally do not extend the error class to create user-defined fault classes. The RuntimeException class represents an error in program code that is extensible and allows the user to create a specific Run-time exception class.
Error (run-time error) and Run-time exception are the same: the Java compiler does not check them, when the program is running, they will terminate the operation.
5. The best solution
For Run-time exceptions, we do not use Try...catch to capture processing, but in the process development debugging phase, as far as possible to avoid this exception, once found that the exception, the correct approach will improve the program design code and implementation, modify the error in the program, so as to avoid this anomaly. Capturing and handling Run-time exceptions is a good solution, because this exception can be avoided by improving code implementations.
For the check exception, do not, honestly to follow the exception handling method to deal with, or use Try...catch to catch and solve, or with throws thrown.
For error (run-time error), do not need to do any processing in the program, after the problem, should be in the program outside the place to find problems, and then solve.
viii. abnormal transformation and abnormal chain
Abnormal transformation has been mentioned above, in fact, after the exception is caught, the exception to the new type of exception to throw, this is generally for the exception of the information more intuitive. Like what:
public void Run () throws myexception{
...
try{
...
}catch (IOException e) {
...
throw new MyException ();
}finally{
...
}
}
Exception chain, in later versions of JDK1.4, the Throwable class supports the exception chain mechanism. Throwable contains a snapshot of the thread execution stack when its thread was created. It also contains a message string giving more information about the error. Finally, it can also contain cause (reason): Another throwable that causes this throwable to be thrown. It is also called an anomaly chain facility, because cause itself will have cause, and so on, forming an anomaly chain, each of which is caused by another exception.
In layman's parlance, the exception chain is the original exception packaging as a new exception class, and in the new exception class encapsulated the original exception class, this is done to find the root cause of the exception.
You can create a custom exception type that contains an exception reason case by using the two constructed methods of Throwable:
Throwable (String message, throwable cause)
Constructs a new throwable with the specified detail message and cause.
Throwable (Throwable cause)
Constructs a new throwable with detailed messages with the specified cause and (cause==null. null:cause.toString ()), which typically contains detailed messages for classes and cause.
Getcause ()
Returns the cause of this throwable, or null if cause is not present or unknown.
Initcause (Throwable cause)
Initializes the cause of this throwable to the specified value.
In the Throwable subclass exception, there are similar construction methods that specify the cause of the exception:
Exception (String message, throwable cause)
Constructs a new exception that specifies detailed messages and causes.
Exception (Throwable cause)
Constructs a new exception based on the specified reason and the detailed message (Cause==null. null:cause.toString ()) (it typically contains cause class and verbose messages).
Therefore, you can construct a new exception class with an exception reason by extending the exception class.
ix. principles and Techniques of Java exception handling
1, avoid too large try block, do not put the exception code into the try block, try to keep a try block corresponding to one or more exceptions.
2, the type of refinement of the exception, do not matter what type of exceptions are written exception.
3, catch block as far as possible to maintain a block to catch a class of exceptions, do not ignore the catch of the exception, caught after either processing, or translation, or to throw out the new type of exception.
4. Do not throw away the exception that you can handle.
5, do not use Try...catch to participate in the program process, the fundamental purpose of the exception control is to deal with the abnormal situation of the program.