Java exception depth understanding and exception handling summary

Source: Internet
Author: User
Tags exception handling finally block stack trace thread class throw exception throwable

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 exception, may be spontaneous, however, 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, After the 1.4 version of the addition of the exception chain mechanism, so as to facilitate the tracking of exceptions! This is the Java Language designer's clever place, is also a Java language difficulty, below is I to Java exception knowledge of a summary, also is a resource recycling.

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 does the exception class come 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.

Where does the exception come 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! For example, 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. If an exception occurs within a try statement block, the exception is thrown, and your code catches the exception in the catch statement block and handles it, and the exception that is generated by some system is 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

}

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!

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.

Class diagram of Java anomaly 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.

Iii. Java exception handling mechanism

There are two ways to handle code that might appear to be abnormal:

First, in the method to catch and handle the exception with the Try...catch statement, the Catach statement 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 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.

Finally, you should also pay attention to the syntax rules for exception handling:

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 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.

Iv. 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, custom Exception class

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 ();
}
}
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.

V. 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 ("Hello world!!!");
try{
System.out.println (1/0);
}catch (ArithmeticException e) {
System.out.println ("divisor is 0!");
}
System.out.println ("Divisor 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 some error classes are defined in the JDK, such as Virtualmachineerror

and OutOfMemoryError, the program itself cannot fix these errors. Typically, you do not extend the error class to create user-defined error 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 examination of abnormal, do not, honestly to follow the exception handling method to deal with, or with try...catch capture and resolution, 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.

Vi. abnormal transformation and abnormal chain

Abnormal transformation in the above has been mentioned, in fact, is to catch an exception, the exception to the new type of exception to throw, this is generally for the exception of the information more intuitive! For example:

 

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 the cause of an exception 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.

Vii. Java exception handling principles and techniques

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 excetpion.

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.


Reprint Address: http://dev.yesky.com/61/8111561.shtml

Contact Us

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.