Java Exception Handling

Source: Internet
Author: User
Tags null null stack trace terminates throw exception throwable

Java Exception Handling summary exception handling is a very important aspect of program design, but also a major difficulty in programming, from C, you may already know how to use if...else ... To control the anomalies, perhaps spontaneously, however, such control is very painful, the same anomaly or false assumptions occur in multiple places, then you have to do the same in every place, feeling quite troublesome! The Java language at the beginning of the design to consider these problems, 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 contains the error concept), define the specification of exception handling, The exception chain mechanism was added after the 1.4 version number, making it easy to track exceptions! This is the genius of the Java language designers, but also a difficulty in the Java language, the following is my Java exception knowledge of a summary, but also 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, if your code is missing a semicolon, then executing the result is a hint of error java.lang.Error; Suppose 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 described later. days have not measured the wind, people have unforeseen, Java program code is also the case. In the process of programming, we should avoid errors and anomalies as far as possible, and how to deal with the unavoidable and non-predicted situations when considering the occurrence of anomalies. The XOR object in Java is used to represent. Java's handling of exceptions is handled by exception, with different exceptions having different classifications, each with a corresponding type (class), and an exception (Class) object for each exception. 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 has customized 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 execution when the environment itself throws the 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 program ape throws itself, this exception can be a program ape custom, can also be defined in the Java language, throw an exception with throw keyword, such a XOR is often used to report to the caller the exception of some information. 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 keywordtry, catch, throw, throws, finally. The basic process is to wrap the statement that you want to monitor with a try statement block, assuming that an exception occurs inside 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 thrown out of the Java runtime itself. You can also declare the method to throw an exception by Throwskeyword on the method, and then throw the exception object through a throw inside the method. The finally statement block runs before the method runs a return, such as the following general structure:
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 multiple exceptions, and then runs the catch statement block when only the exception on the match is run. The type of catch is defined in the Java language, or the program Ape is custom, representing the type of the code that throws the exception, the exception variable name represents the reference to the object that throws the exception, and assuming that the catch captures and matches the exception, then the exception variable name can be used directly, at which point the exception variable name points to the matching 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 the robustness of the program, and you can give the program a chance to fix it in the catch and finally code blocks, so that the program does not terminate with an exception or change beyond the process. At the same time, by getting Java exception information, but also for the development and maintenance of the program to provide a convenient, generally through the exception information is very fast to find the problem (code) where the exception occurs. Java exception Handling is a major feature of the Java language, but also a difficult one, mastering exception handling can make writing code more robust and easy to maintain. ii. Java Exception class diagramThe following 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. only when an object is an instance of this class (or one of its subclasses), talent is thrown through a Java virtual machine or Java throw statement. Similarly, only one of the talents in this class or its subclasses is sufficient to be the type of the parameter in the catch clause. examples of two subclasses, Error and Exception, are often used to indicate that an exception has occurred. Typically, these instances are newly created in the context of the exception, and therefore include 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. While running the method, there is no need to declare in the method whatever subclass of the Error that might be 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 no practical try...catch statement captures it, There is no practical throws sentence declaration to throw it, or will compile through. 4, RuntimeException
RuntimeException is a superclass of exceptions that might be thrown during the normal execution of a Java virtual machine. The Java compiler does not check it, that is, when this kind of exception can occur in the program, even if there is no practical try...catch statement to capture it, there is no practical throws sentence declaration to throw it, or will compile through, such an exception can be improved code implementation to avoid. 5, Threaddeath
when a stop method with 0 parameters is called 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. Assuming that Threaddeath is captured by a method, it is important to throw it again, because the ability to actually terminate the thread. Assuming that 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 Error and not a subclass of Exception, because many applications capture all occurrences of Exception and then discard them. the above is an introduction to the exception API, the use of the method is very easy, the key is to understand the principle of exception handling, detailed use of methods to refer to 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 ();
}
}  Assuming that each method is simply throwing an exception, in a multi-layered call to the method invocation method, the java Virtual opportunity is searched back from the method code block in which the exception occurred, until it finds the block of code that handles the exception. The exception is then handed to the corresponding catch statement for processing. Assuming that the Java virtual machine is traced back to the bottom of the method call stack main () method, it is assumed that the code block that handles the exception is still not found and will be handled as follows:
First, the Printstacktrace () method of the object that called the exception prints the exception information for the method call stack.
Second, assuming that the thread that is the exception is the main course, the entire program terminates, assuming that the thread is not the main path, and the other threads continue to execute. through analysis, we can see that the earlier the process 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. another point that cannot be overlooked is the code that the finally statement must run under whatever circumstances, which guarantees the reliability of the code that must be run under no circumstances. For example, when a database query is abnormal, you should release the JDBC connection and so on. The finally statement runs before the return statement, regardless of its precedence, and whether or not the try block has an exception. The only case where the finally statement is not run is if the method runs 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 makes it meaningless and easy to cause an error. Finally, you should pay attention to the syntax rules for exception handling:
first, try statement can not exist alone, can and catch, finally make up try...catch...finally, Try...catch, try...finally Three kinds of structure, catch statement can have one or more, Finally, at most one, the three keyword of try, catch, finally cannot be used alone. the scope of the variables in the second, try, catch, finally three blocks of code is independent and cannot be interviewed by one another. If you want to be able to access in three blocks, you need to define the variables outside of those blocks. third, multiple catch blocks, when a Java virtual opportunity matches an exception class or its subclasses, it runs the catch block without running another catch block. after the throw statement does not agree with the other statements immediately following, because these do not have the opportunity to run. Fifth, if a method invokes another method that declares an exception, this method either handles the exception or throws the declaration. How do you infer that a method might be abnormal? in general, the method declaration with the throws statement, the method has a throw statement, method call method declaration has throwskeyword. The difference between throw and Throwskeyword
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. Define your own exception class
Create a subclass of exception or RuntimeException to get an exception class of your own definition. Like what:
Public class MyException extends exception{
Public myexception () {}
Public MyException (String SMG) {
Super (SMG);
}
} 3. Use your own defined exceptions
declaring the method with throws may throw its own defined exception, and throw it in the appropriate place with its own defined exception. 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 ();
}
} Another code, very interesting:
public void Test2 () throws myexception{
...
try {
...
} catch (MyException e) {
Throw e;
}
}

This code actually captures the exception, and then come clean, without a point, assuming that there is any merit in this, do not deal with it, directly before the method with the throws declaration thrown out. The catch of the anomaly is going to be done with some meaningful processing. v. Exception at execution and check exception
The exception class can be divided into two types: execution-time exceptions and checked exceptions.
1. Exception at execution time
The RuntimeException class and its subclasses are called execution-time exceptions, and the exception is that the Java compiler does not check it, that is, when such an exception may occur in the program, even if no practical try...catch statement captures it, There is no practical throws sentence declaration to throw it, or will compile through. For example, when the divisor is zero, a Java.lang.ArithmeticException exception is thrown. 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
An execution-time exception indicates that an exception cannot be resumed by the program, and the cause of such an exception is generally due to an incorrect operation being performed. Once an error occurs, it is recommended that the program be terminated.
A check exception indicates an exception that the program can handle. Assuming that 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 captured and processed by a program, such as a zero-divisor execution-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!!!");
}
}Execution Result:
Hello World!!!
Divisor is 0!
Divisor is zero after the program did not terminate ah, hehe!!! 4. Error during execution
The error class and its subclasses represent an execution-time error, typically thrown by a Java virtual machine, and some of the wrong classes are defined in the JDK, for example 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 allows the user to create a specific execution-time exception class.
The same thing about error (Execution-time error) and execution-time exceptions is that the Java compiler does not check them and terminates execution when the program executes.
5. The best way to solve
for the execution of the exception, we do not use Try...catch to capture processing, but in the program development debugging phase, as far as possible to avoid such an exception, once the exception is found, the correct practice will improve the design of the Code and Implementation methods, change the program errors, so as to avoid such an exception. Capturing and handling execution-time exceptions is a good solution, because it can be avoided by improving the implementation of the Code. 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 (execution errors), do not need to do any processing in the program, after a failure, should be in the outside of the program to find the problem, and then solve. vi. abnormal transformation and abnormal chainAbnormal 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! Example:
Public Void Run () throws myexception{
...
try{
...
}catch (IOException e) {
...
throw new MyException ();
}finally{
...
}
} exception Chain , in the JDK1.4 version number, the Throwable class supports the exception chaining mechanism. Throwable includes a snapshot of the thread's run stack when its thread was created. It also includes a message string that gives a lot of other information about the error. Finally, it can also include cause (reason): There is also a throwable that causes this throwable to be thrown. It is also known as the anomaly chain facilities, because cause itself will have cause, and so on, the formation of an abnormal chain, each exception is caused by an 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.
        Through the two constructor methods of Throwable, you can create your own defined exception types that include the cause of the exception :
Throwable (String message, Throwable cause)
          constructs a new throwable with specific messages and cause specified.
Throwable (throwable cause)
          constructs a zone with the specified cause and (cause== Null? Null:cause.toString ()) (it usually includes the class and cause specific messages) for the new throwable of the specific message.
Getcause ()
          returns the cause of this throwable; if cause is not present or unknown, it returns Null.
Initcause (throwable cause)
          cause this Throwable Initialized 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 a specific message and reason specified.
Exception (Throwable cause)
Constructs a new exception based on the specified reason and the specific message (Cause==null null:cause.toString ()), which typically includes the cause class and the specific message.
Therefore, it is possible to 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, refinement of the type of the exception, no matter 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 throw a new type of exception.
4. Don't throw the exception that you can handle to others.
5, do not use try...catch participation and control procedures, the fundamental purpose of exception control is to deal with the abnormal situation of the program. References
mainly Java API documentation (version 1.5), and some of the books I have seen before, there are some other scattered information. Maine-books are:
JAVA2 references
Thinking in Java
Java Core Technology (vol. 1)

Source: http://lavasoft.blog.51cto.com/62575/18920/

Java Exception Handling

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.