Java Exception Supplements

Source: Internet
Author: User
Tags finally block throw exception 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 , including the type of error, where it occurred. A series of information such as program status.

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

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


When the third method is called, an exception is thrown, and the runtime will reverse the call stack to find the handler for the exception, when the exception type is consistent with the type of exception declared by an exception handler. The system then gives the exception to it for processing.


Assuming the system is not able to find the appropriate exception handler, the system will terminate.

Exception type

Java provides two ways to handle exceptions:

(1) Use a try statement to catch the exception and handle it.

(2) Use Throwskeyword to list the type of exception to throw, which means no processing is done within this method. However, 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 processed.

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. 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. Thrown java.io.FileNotFoundException, the application should catch this exception and alert the user. A similar anomaly belongs to checked exception.

except for the Error, RuntimeException , and the 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 because of 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, a sample file operation. Because of a logic error, the incoming file name is a null value, and the program throws a nullpointerexception.

Although it is possible to allow the program to 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 the capture of unchecked exception is not necessary . 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 subclass of Indexoutofboundsexception,runtimeexception. Unchecked exception type, not the out.println that must be captured            ("Value at:" + i + "=" + List.get (i));        }        Out.close ();         } catch (IOException e) {  //capture IOException ...         }    }}

Unchecked exception can also choose to capture it in some special cases, such as the above program, which now captures IOException and captures Indexoutofboundsexception. Overrides such as the following:

public void Writelist () {         try{         ///FileWriter constructor method throws IOException, checked exception type. Must capture        printwriter out = new PrintWriter (New FileWriter ("OutFile.txt"));         for (int i = 0; i < SIZE; i++) {            //get (int) method throws indexoutofboundsexception. The subclass of the runtimeexception. Unchecked exception 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 ...         }

Suppose that the exception that is caught at the same time has an inheritance relationship, that is, an exception when there is a subclass of the exception, you must write the parent exception after the subclass exception , otherwise the compilation error will be reported.

But. No matter how many capture statements, you can finally enter a catch statement at most.

Like what:

public class Example {public           void Test () throws ioexception{             throw new IOException ();           public static void Main (String args []) {                         Example Example  = new Example ();                         try {                    example.test ();             } catch (IOException e) {                    System.out.println ("Child exception caught");             } catch (Exception e) {                    System.out.println ("Caught parent exception");}}             }     

In the above example, IOException is a subclass of exception, assuming that the method throws a IOException exception, enters the first catch clause, but does not enter the second catch statement Suppose to throw a non-ioexception other exception subclass exception. The second catch clause is entered directly.

That is, it does not enter two catch clauses at the same time .


after Java SE 7 , a catch block can catch multiple exceptions. The above capture statement can be abbreviated as:

catch (Indexoutofboundsexception | IOException ex) {    ...}
It is important to note that in such cases, the catch parameter ("Ex" in the previous example) is final by default. It is not possible to assign a value to it again in a catch block.

The finally code block runs when the try block exits, regardless of whether the exception occurs. Often used to release resources. Like what:

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 run complete

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

It is important to note that the JVM exits when the Try-catch code block is run. Or the thread that runs the Try-catch code block is interrupted or killed. or use the System.exit () function, and so on. finally blocks of code may not be run .

A try-catch-finally block is used in a function with a return value, and the return value is related to whether an exception occurred, you should avoid writing the return value in the finally block, because the return value of the finally block will be followed regardless of whether an exception occurs. Instead of ignoring the return value of Try-catch wherever it is. Like what:

public int test () {                         inputstream in = null;             try {                    file F = new File ("F:\test.txt");                    in = new FileInputStream (f);                     return 1;              } catch (IOException e) {                    e.printstacktrace ();                    return 2;             } finally{                    try {                           in.close ();                    } catch (IOException e) {                           e.printstacktrace ();                    }                    return 3;             }      }

In the example above, No 1 or 2 is returned, regardless of whether the ioexception is thrown, and only 3 is returned.

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.

Start with Java 7. provides a more concise and effective notation: try-with-resources statements.

Use forms such as the following:

static string Readfirstlinefromfile (string path) throws IOException {    try (bufferedreader br =                   New BufferedReader (new FileReader)) {        return br.readline ();    }}
Try-with-resources ensure that the program within {} is actively shutting down its resources after it has been run, and all Java.lang are implemented. autocloseableInterface (Java 7 new interface, Java.lang.Closeable's parent interface. ) object can be used as a resource.


Throw and throws

An exception is caught if a method throws an exception.

Throwkeyword is used to throw an exception where the 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. It is not possible to do this if the stack is empty. Therefore, the emptystackexception exception is thrown.

When other methods call the Pop () method. It should be considered that the pop () may throw an exception, assuming that pop () throws the uncheckedexception, can not do extra processing, assuming that pop () is thrown by checked exception must be processed, can be captured with Try-catch , it is also possible to choose not to capture within this method and continue to throw with Throwskeyword. Such as:

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

In fact, an exception is very often caused by a cause exception. Because cause itself will have cause. And so on, a chain exception (Chained Exceptions)is formed.

Like what:

try {

} catch (IOException e) {//Capture to IOException, throw an exception

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

}

Throwable has a constructor capable of accepting the Throwable type as the initcause(throwable),getcause() of the Cause,throwable class that caused the exception. Ability to set cause information and get cause information.


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.