Java Exception Supplements

Source: Internet
Author: User
Tags finally block throwable java se

Overview

When an error occurs inside a method, the method creates an object that is passed to the runtime system, which is called the exception object , containing a series of information such as the type of error, where it occurred, and the state of the program.

When a method throws an exception, the runtime looks for the exception to be handled along the call stack .

, the call stack below method calls the above method, layered layer nesting, altogether four layers:


When the third method is called, an exception is thrown, and the runtime looks backwards at the call stack to find the handler for the exception, which is given to the exception type when the exception type is the same as the exception that is declared by a handler.


If the system does not find an appropriate exception handler, the system will terminate.

Exception type

Java provides two ways to handle exceptions:

(1) Use a try statement to catch exceptions and handle them;

(2) Use the throws keyword to list the type of exception to throw, which means no processing is done within this method, but the method that calls the method must either handle the exception or continue to throw.

not all exceptions need to be explicitly processed (the processing represented here is captured or thrown inside the program), such as IOException, SqlException, etc., which must be handled, and NullPointerException, ArithmeticException, indexoutofboundsexception and so on can not be treated.

To understand this, the basic classification of anomalies is to be clarified.


Checked Exception

Such exceptions are errors that the application can foresee and be able to recover, for example, the application requires the user to enter a file name, and the program will read and write the file. If the user enters a file name that does not exist and throws Java.io.FileNotFoundException, the application should catch the exception and alert the user. Similar to this anomaly belongs to checked exception.

except for the Error, RuntimeException , and subclasses of both, all exceptions belong to checked exception.


Error

Error is generally an exception caused by an application that is not normally foreseen and recoverable. For example, the program successfully opened a file, but due to hardware or operating system failure, can not read the contents of the file, the program will throw Java.io.IOError.


Runtime Exception

RuntimeException is generally the exception that is caused by the program , and the application is usually predictable and recoverable. The presence of such anomalies generally implies a bug in the program. For example, as an example of a file operation, because of a logic error, the incoming file name is NULL, and the program throws a nullpointerexception.

While it is possible to have the program capture RuntimeException, it is more appropriate to remove the bug that caused such an exception.

The Java exception class hierarchy diagram is as follows:



Catch of exceptions

Checked Exception must be captured, and Unchecked Exception The capture is not required . For example:

Import Java.io.*;import Java.util.list;import java.util.ArrayList; public class Listofnumbers {     private list<integer> List;    private static final int SIZE = ten;     Public Listofnumbers () {        list = new arraylist<integer> (SIZE);        for (int i = 0; i < SIZE; i++) {            list.add (new Integer (i));        }    }     public void Writelist () {         try{         ///FileWriter constructor method throws IOException, checked exception type, must be captured        PrintWriter out = new PrintWriter (New FileWriter ("OutFile.txt"));         for (int i = 0; i < SIZE; i++) {            //get (int) method throws Indexoutofboundsexception,runtimeexception subclass, unchecked excep tion type, not the out.println that must be captured            ("Value at:" + i + "=" + List.get (i));        }        Out.close ();         } catch (IOException e) {  //capture IOException ...         }    }}

Unchecked exception in some special cases can also choose to capture it, such as the above program, now both capture IOException, but also to capture indexoutofboundsexception, rewritten as follows:

public void Writelist () {         try{         ///FileWriter construction method throws IOException, checked exception type, must be captured        PrintWriter out = new PrintWriter (New FileWriter ("OutFile.txt"));         for (int i = 0; i < SIZE; i++) {            //get (int) method throws Indexoutofboundsexception,runtimeexception subclass, unchecked except Ion type, not the out.println that must be captured            ("Value at:" + i + "=" + List.get (i));        }        Out.close ();         } catch (Indexoutofboundsexception e) {  //capture indexoutofboundsexception ...         } catch (IOException e) {  //capture IOException ...         }

from Java SE 7 , a catch block can catch multiple exceptions, and the above capture statements can be abbreviated as:

catch (Indexoutofboundsexception | IOException ex) {    ...}
It is important to note that in this case, the catch parameter ("Ex" in the previous example) is final by default and cannot be assigned again in the catch block.

The finally code block executes whenever the try code block exits, regardless of whether the exception occurs, and is often used to free resources. For example:

public void Writelist () {       printwriter out = null;    try{      out = new PrintWriter (New FileWriter ("OutFile.txt"));       for (int i = 0, i < SIZE; i++) {          out.println ("Value at:" +i + "=" + List.get (i));      }         } catch (IOException e) {            ...    } finally{  //release resource             if (out!=null) {                    out.close ();}}  }

In the above example, there are three scenarios that can cause a try code block to exit:

(1) newfilewriter ("OutFile.txt") throws IOException

(2) List.get (i) throw indexoutofboundsexception

(3) No exception thrown, code execution complete

Regardless of the situation above, the runtime system guarantees that the program in the finally code block will execute.

It is important to note that if the JVM exits when the Try-catch code block is executed, or if the thread executing the Try-catch code block is interrupted or killed, thefinally block of code may not be executed .

Try-with-resources statements

One or more resources declared in a try should be closed after the program finishes, usually in the finally block of code.

starting with Java 7, there is a more concise and efficient way to do this: try-with-resources statements.

Use the following form:

static string Readfirstlinefromfile (string path) throws IOException {    try (bufferedreader br =                   New BufferedReader (new FileReader)) {        return br.readline ();    }}
Try-with-resources ensure that the program is automatically closed after execution of the {} and all Java.lang are implemented. autocloseableThe objects of the interface (Java 7 new interface, Java.lang.Closeable's parent interface,) can be used as resources.


Throw and throws

An exception is caught if a method throws an exception.

The Throw keyword is used to throw an exception where an error occurs inside the method body. Such as:

Public Object pop () {    object obj;     if (size = = 0) {  //stack is empty, throw exception        throw new Emptystackexception ();    }     obj = Objectat (size-1);    Setobjectat (size-1, null);    size--;    return obj;}
This method is used to eject the top element of the stack from the stack, but if the stack is empty it cannot be done, so a emptystackexception exception is thrown.

When other methods call the Pop () method, you should take into account the exceptions that pop () may throw, and if pop () throws a uncheckedexception, you can do no extra processing if pop () throws checked Exception must be processed, can be captured with try-catch, or you can choose not to capture within this method, and continue to be thrown with the throws keyword, such as:

public void Callpop () throws Emptystackexception {...      Pop (); The method may throw emptystackexception ...      }

In fact, an exception is often caused by another cause exception, because cause itself will have cause, and so on, forming a chain exception (Chained Exceptions). For example:

try {

} catch (IOException e) {//catches to IOException, throws another exception

throw new Sampleexception ("Other IOException", e);

}

Throwable has a constructor that can accept parameters of the Throwable type as initcause(throwable),getcause() of the Cause,throwable class that caused the exception You can set cause information and get cause information.


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Java Exception Supplements

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.