Java Basics-Exception Handling Summary

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

Exception handling is a very important aspect in program design, and it is 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 very 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 in the design of the original consideration of these issues, the exception of the framework of the scheme, all the exceptions can be represented by a type, different types of exceptions corresponding to different subclass exceptions (here The exception includes the concept of error), define the specification of exception handling, After the 1.4 version 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 my Java exception knowledge of a summary, is also considered a resource recovery.

I. Basics of Java Exceptions

Exceptions are errors in the program, but not all errors are exceptions, and errors can sometimes be avoided. For example, your code is missing a semicolon, then running out of the result is the hint is error java.lang.Error; If you use System.out.println (11/0), then you are because you use 0 to do the divisor, Throws a Java.lang.ArithmeticException exception.

Some exceptions need to be handled, others do not need to be captured, and are discussed in detail later.

The sky is rainy, people have unforeseen, Java program code is also the case. In the process of programming, we should avoid errors and anomalies as much 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. Java's handling of exceptions is handled by exception, with different categories of exceptions, each of which corresponds to a type (class), and each exception corresponds to an exception (Class) object.

Where does the exception class come from? There are two sources, one is some of the basic exception types 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 identifies the conditions that a reasonable application wants to capture.

Where does the exception object 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 himself, which can be defined by the programmer itself, or it can be defined in the Java language, and throws an exception 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 throwing, catching, and handling exceptions are all done in the method.

Java exception handling is managed by 5 keyword try, catch, throw, throws, finally. The basic process is to wrap the statement that you want to monitor with a try statement block, and if an exception occurs within a try statement block, the exception is thrown, your code can catch the exception in the Catch statement block, 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 on the method, and then throw the exception object through a throw inside the method. The finally statement block executes before the method executes a 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, which matches more than one of the above, and executes the CATCH statement block only when the exception on the match is executed. The type of catch is defined in the Java language or is defined by the programmer itself, indicating that the code throws an exception, the exception variable name represents the reference to the object that throws the exception, and if the catch catches and matches the exception, then the exception variable name can be used directly. At this point 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, you can give the program a remediation opportunity in the catch and finally code block, so that the program does not terminate due to an exception or changes outside the process. At the same time, by obtaining the Java exception information, but also for the development and maintenance of the program to provide a convenient, generally through the exception information can quickly find the problem (code) where the exception.

Java exception handling is a major feature of the Java language, but also a difficult one, mastering exception handling can make the written code more robust and easy to maintain.

Ii. Java Exception class diagram

Here are the hierarchical graphs 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. A Java Virtual machine or Java Throw statement can only be thrown if the object 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.

Instances of two subclasses, Error, and Exception, are typically used to indicate an abnormal condition has occurred. Typically, these instances are newly created in the context of the exception and therefore contain relevant information (such as stack trace data).

2, Exception

The Exception class and its subclasses are a form of throwable that identifies the conditions that a reasonable application wants to capture, indicating the exceptions that the program itself can handle.

3. Error

Error is a subclass of Throwable that represents a serious problem that cannot be recovered by the program itself, and is used to indicate that a reasonable application should not attempt to capture a serious issue.

During the execution of this method, there is no need to declare in the method any subclasses of the Error that might have been thrown but not captured by throws, 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, Nor does it use the throws sentence declaration to throw it, or it will be compiled through.

4, RuntimeException

RuntimeException is a superclass of exceptions that might 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 the program, even if it is not captured with the Try...catch statement, it is not thrown with the throws sentence declaration, or it is compiled through, this exception can be avoided by improving the code implementation.

5, Threaddeath

When you call the Stop method with the 0 parameter in the thread class, the victim thread throws an Threaddeath instance.

An instance of this class should only be captured if the application must be purged after it has been terminated asynchronously. If the Threaddeath is captured by a method, it is important to re-throw it, because that will allow the thread to actually terminate.

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 and not a subclass of Exception, 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.

Third, Java exception handling mechanism

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

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 exceptions 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, the Java virtual Opportunity in the multi-layered nested invocation of the method invocation method is searched back from the method code block in which the exception occurred until a block of code handling the exception is found. The exception is then handed to the appropriate catch statement for processing. If the Java virtual machine goes back to the bottom of the method call stack, the main () method, if you still do not find a code block to handle the exception, follow these steps:

First, the Printstacktrace () method of the object that called the exception prints the exception information for the method call stack.

Second, if the thread that has the exception is the main course, the entire program terminates, and if it is not the main thread, the other thread continues to run.

Through analysis, we can see that the earlier the processing of abnormal consumption of resources and time, the smaller the scope of the impact. Therefore, do not throw exceptions that you can handle to the caller.

Also, it is important not to overlook the code that the finally statement must execute in any case, which guarantees the reliability of the code that 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 precedence, or whether the try block has an exception. The only case where the finally statement 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. A finally statement block cannot change the return value of a return by assigning a new value to the variable, and it is also recommended that you do not use the return statement in the finally block, which is meaningless and prone to errors.

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

The first, try statement can not exist alone, and catch, finally make up try...catch...finally, Try...catch, try...finally Three kinds of structure, catch statement can have one or more, The finally statement has at most one, and the try, catch, finally three keywords cannot be used alone.

The scope of the variables in the second, try, catch, finally three blocks of code is independent and cannot be accessed from one another. If you want to be accessible in three blocks, you need to define the variables outside of those blocks.

Third, multiple catch blocks, when a Java virtual opportunity matches one of the exception classes or its subclasses, executes the catch block without executing another catch block.

The throw statement is not allowed to follow the other statements, since these do not have a chance to execute.

If a method invokes another method that declares an exception, the method either handles the exception or throws the declaration.

How can you tell if a method might be abnormal? In general, the method declaration is used with the throws statement, the method has a throw statement, method calls method declaration has the throws keyword.

The difference between the 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 Classes

Creating a subclass of exception or runtimeexception will give you a custom exception class. For example:

 

public class MyException extends exception{
Public myexception () {}
Public MyException (String SMG) {
Super (SMG);
}
}
3. Using a Custom exception

Declaring a method with throws may throw a custom exception, and throw a custom exception in the appropriate place with a throw statement. For example:

Throws an exception in a certain condition

public void Test1 () throws myexception{
...
if (...) {
throw new MyException ();
}
}
Transform anomalies (also called translations), making exceptions easier to read and easy 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 come clean, there is no point, if there is nothing to deal with, do not deal with the line, directly before the method with the throws declaration is thrown. The catch of the anomaly is going to be done with some meaningful processing.

V. Run-time exceptions and check exceptions

The exception class can be divided into two types: run-time exceptions and checked exceptions.

1. Run-time exception

The RuntimeException class and its subclasses are called run-time exceptions, and the exception is characterized by the Java compiler not checking it, that is, when such an exception can occur in a program, even if it is not captured with a try...catch statement, it is not thrown with the throws clause declaration , or it will be compiled through. For example, a Java.lang.ArithmeticException exception is thrown when the divisor is zero.

2. Check exception

In addition to the RuntimeException class and its subclasses, 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, or the compilation does not pass.

3, the difference between the two

A run-time exception indicates an exception that cannot be resumed by the program, and the cause of this exception is usually due to an incorrect operation. Once an error occurs, it is recommended that the program be terminated.

A check exception indicates an exception that the program can handle. If the method that throws the exception itself does not handle it or cannot handle it, then the caller of the method must handle the exception, otherwise the call will go wrong and the compilation will fail. Of course, both of these exceptions can be caught and processed by a program, such as a zero-divisor run-time exception:

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 is zero after the program did not terminate ah, hehe!!!");
}
}
Operation Result:
Hello World!!!
Divisor is 0!
Divisor is zero after the program did not terminate ah, hehe!!!
4. Run-time error

The error class and its subclasses represent run-time errors, usually thrown by a Java virtual machine, with some wrong classes defined in the JDK, 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. While the RuntimeException class represents an error in the program code, it is extensible, and the user can create a specific runtime exception class.

The same thing about error (run-time errors) and run-time exceptions is that the Java compiler does not check them and will terminate when the program runs.

5, the best solution

For run-time exceptions, we do not use Try...catch to capture processing, but in the program development debugging phase, try to avoid this exception, once the exception is found, the correct practice will improve the design of the Code and Implementation methods, modify the program errors, so as to avoid this exception. Capturing and handling runtime exceptions is a good solution because you can avoid this kind of exception by improving your code implementation.

For the check exception, didn't see?, honestly go according to the method of exception handling, either capture and solve with try...catch, or throw with throws!

For error (Run-time error), do not need to do any processing in the program, after the problem, should be in the outside of the program to find the problem, and then solve.

Vi. abnormal transformation and abnormal chain

The exception transformation has been mentioned above, in fact, after catching an exception, the exception is thrown with a new type of exception, 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 JDK1.4 later versions, the Throwable class supports the exception chaining mechanism. Throwable contains a snapshot of the thread execution stack when its thread was created. It also contains a message string that gives more information about the error. Finally, it can also contain cause (reason): Another throwable that causes this throwable to be thrown. It is also known as the anomaly chain facility, because cause itself also has cause, and so on, it forms an exception chain, each exception is caused by another exception.

In layman's words, the exception chain is to wrap the original exception as a new exception class, and to encapsulate the original exception class in the new exception class, in order to find the root cause of the exception.

You can create a custom exception type that contains the cause of the exception by using the two construction methods of Throwable:

Throwable (String message, throwable cause)

Constructs a new throwable with the specified verbose message and cause.

Throwable (Throwable cause)

Constructs a new throwable with a detailed message with the specified cause and (cause==null. null:cause.toString ()) (which usually contains the details of the class and cause).

Getcause ()

Returns the cause of this throwable, or null if cause does not exist or is unknown.

Initcause (Throwable cause)

Initializes the cause of this throwable to the specified value.

In the subclass exception of Throwable, there is a similar construction method for specifying the cause of the exception:

Exception (String message, throwable cause)

Constructs a new exception with the specified detail message and reason.

Exception (Throwable cause)

Constructs a new exception based on the specified reason and detailed message (Cause==null. null:cause.toString ()), which typically contains cause classes and verbose messages.

Therefore, you can construct a new exception class with an exception cause by extending the exception class.

Vii. principles and Techniques for Java exception handling

1, avoid too large try block, do not put the code will not appear in the try block, try to keep a try block corresponding to one or more exceptions.

2, refine the type of the exception, not regardless of what type of exception are written excetpion.

3, catch block as far as possible to keep a block catch a class of exceptions, do not ignore the caught exception, capture to either process, or translate, or re-throw the new type of exception.

4. Don't throw the exception that you can handle to others.

5, do not use Try...catch to participate in control procedures, the fundamental purpose of exception control is to deal with the abnormal situation of the program.

Java Basics-Exception Handling Summary

Related Article

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.