Java Exception Study

Java Exception

<!--[if !supportLists]-->1.       <!--[endif]-->Call Stack

The set of possible "somethings" to handle the exception is the ordered list of methods that had been called to get to the method where the error occurred. The list of methods is known as the call stack (see the next figure)

<!--[if gte vml 1]><v:shapetype id="_x0000_t75" coordsize="21600,21600" o:spt="75" o:preferrelative="t" path="m@4@5l@4@11@9@11@9@5xe" filled="f" stroked="f"> <v:stroke joinstyle="miter" /> <v:formulas> <v:f eqn="if lineDrawn pixelLineWidth 0" /> <v:f eqn="sum @0 1 0" /> <v:f eqn="sum 0 0 @1" /> <v:f eqn="prod @2 1 2" /> <v:f eqn="prod @3 21600 pixelWidth" /> <v:f eqn="prod @3 21600 pixelHeight" /> <v:f eqn="sum @0 0 1" /> <v:f eqn="prod @6 1 2" /> <v:f eqn="prod @7 21600 pixelWidth" /> <v:f eqn="sum @8 21600 0" /> <v:f eqn="prod @7 21600 pixelHeight" /> <v:f eqn="sum @10 21600 0" /> </v:formulas> <v:path o:extrusionok="f" gradientshapeok="t" o:connecttype="rect" /> <o:lock v:ext="edit" aspectratio="t" /> </v:shapetype><v:shape id="Picture_x0020_1" o:spid="_x0000_i1030" type="#_x0000_t75" alt="The call stack showing three method calls, where the first method called has the exception handler." style='width:163.5pt;height:183.75pt;visibility:visible;mso-wrap-style:square'> <v:imagedata src="file:///C:\Users\bli3\AppData\Local\Temp\msohtmlclip1\01\clip_image001.gif" o:title="The call stack showing three method calls, where the first method called has the exception handler" /> </v:shape><![endif]--><!--[if !vml]-->The call stack showing three method calls, where the first method called has the exception handler.<!--[endif]-->

 

<!--[if !supportLists]-->2.       <!--[endif]-->Catch the Exception

The exception handler chosen is said to catch the exception. If the runtime system exhaustively searches all the methods on the call stack without finding an appropriate exception handler, as shown in the next figure, the runtime system (and, consequently, the program) terminates.


 

<!--[if gte vml 1]><v:shape id="Picture_x0020_4" o:spid="_x0000_i1029" type="#_x0000_t75" alt="The call stack showing three method calls, where the first method called has the exception handler." style='width:257.25pt;height:184.5pt;visibility:visible;mso-wrap-style:square'> <v:imagedata src="file:///C:\Users\bli3\AppData\Local\Temp\msohtmlclip1\01\clip_image002.gif" o:title="The call stack showing three method calls, where the first method called has the exception handler" /> </v:shape><![endif]--><!--[if !vml]-->The call stack showing three method calls, where the first method called has the exception handler.<!--[endif]-->

 

<!--[if !supportLists]-->3.       <!--[endif]-->Specifying the Exceptions Throw by a method

The throws clause comprises the throws keyword followed by a comma-separated list of all the exceptions thrown by that method.

 

public void writeList() throws IOException {

                                PrintWriter out = new PrintWriter(new FileWriter("OutFile.txt"));

 

                                for (int i = 0; i < SIZE; i++) {

                                                out.println("Value at: " + i + " = " + list.get(i));

                                }

                                out.close();

}

ArrayIndexOutOfBoundsException is an unchecked exception; including it in the throws clause is not mandatory.

 

<!--[if !supportLists]-->4.       <!--[endif]-->Three kinds of exception

<!--[if !supportLists]-->1)      <!--[endif]-->Checked Exception

These are exceptional conditions that a well-written application should anticipate and recover from.

<!--[if !supportLists]-->2)      <!--[endif]-->Error

These are exceptional conditions that are external to the application, and that the application usually cannot anticipate or recover from.

Errors are not subject to the Catch or Specify Requirement. Errors are those exceptions indicated by Error and its subclasses.

<!--[if !supportLists]-->3)      <!--[endif]-->RuntimeException

These are exceptional conditions that are internal to the application, and that the application usually cannot anticipate or recover from. These usually indicate programming bugs.

Runtime exceptions are not subject to the Catch or Specify Requirement. Runtime exceptions are those indicated by RuntimeException and its subclasses.

 

<!--[if !supportLists]-->5.       <!--[endif]-->Try-Catch-Finally

 

try {

 

// The try statement should contain at least one catch block or a finally block and may have multiple catch blocks.

 

} catch (ExceptionType name) {

 

} catch (ExceptionType name) {

 

} finally {

 

}

 

Handler:

Each catch block is an exception handler and handles the type of exception indicated by its argument. The argument type, ExceptionType, declares the type of exception that the handler can handle and must be the name of a class that inherits from the Throwable class. The handler can refer to the exception with name.

 

Notes

The runtime system checks writeList's handlers in the order in which they appear after the sstry statement.

 

Finally Clause:

finally is useful for more than just exception handling it allows the programmer to avoid having cleanup code accidentally bypassed (绕过) by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

 

Note: If the JVM exits while the try or catch code is being executed, then the finallyblock may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.

 

Important: The finally block is a key tool for preventing resource leaks. When closing a file or otherwise recovering resources, place the code in a finally block to ensure that resource is always recovered.

If you are using Java SE 7 or later, consider using the try-with-resources statement in these situations, which automatically releases system resources when no longer needed. has more information.

 

 

Java 7 new feature:  avoid duplicating code.

catch (IOException|SQLException ex) {

    logger.log(ex);

    throw ex;

}

 

<!--[if !supportLists]-->6.       <!--[endif]-->Try –with-resources statement

 

The try-with-resources statement is a try statement that declares one or more resources. Aresource is as an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements the java.lang.AutoCloseable interface can be used as a resource

 

  try (BufferedReader br = new BufferedReader(new FileReader(path))) {

    return br.readLine();

  }

}

 

<!--[if !supportLists]-->7.       <!--[endif]-->Throw Exceptions

throw someThrowableObject;

<!--[if gte vml 1]><v:shape id="Picture_x0020_7" o:spid="_x0000_i1028" type="#_x0000_t75" alt="The Throwable class and its most significant subclasses." style='width:285pt;height:165pt;visibility:visible;mso-wrap-style:square'> <v:imagedata src="file:///C:\Users\bli3\AppData\Local\Temp\msohtmlclip1\01\clip_image003.gif" o:title="The Throwable class and its most significant subclasses" /> </v:shape><![endif]--><!--[if !vml]-->The Throwable class and its most significant subclasses.<!--[endif]-->

 

 

 

 

 

 

<!--[if !supportLists]-->8.       <!--[endif]-->Exception chains

 

An application often responds to an exception by throwing another exception. In effect, the first exception causes the second exception. It can be very helpful to know when one exception causes another. Chained Exceptions help the programmer do this.

The following are the methods and constructors in Throwable that support chained exceptions.

Throwable getCause()

Throwable initCause(Throwable)

Throwable(String, Throwable)

Throwable(Throwable)

ccessing Stack Trace Information

Now let's suppose that the higher-level exception handler wants to dump the stack trace in its own format.


Definition:  A stack trace provides information on the execution history of the current thread and lists the names of the classes and methods that were called at the point when the exception occurred. A stack trace is a useful debugging tool that you'll normally take advantage of when an exception has been thrown.


The following code shows how to call the getStackTrace method on the exception object.

catch (Exception cause) {

    StackTraceElement elements[] = cause.getStackTrace();

    for (int i = 0, n = elements.length; i < n; i++) {      

        System.err.println(elements[i].getFileName() + ":"

                      + elements[i].getLineNumber()

                      + ">> "

                      + elements[i].getMethodName() + "()");

    }

}

Logging API

The next code snippet logs where an exception occurred from within the catch block. However, rather than manually parsing the stack trace and sending the output to System.err(), it sends the output to a file using the logging facility in the java.util.logging package.

try {

    Handler handler = new FileHandler("OutFile.log");

    Logger.getLogger("").addHandler(handler);

   

} catch (IOException e) {

    Logger logger = Logger.getLogger("package.name");

    StackTraceElement elements[] = e.getStackTrace();

    for (int i = 0, n = elements.length; i < n; i++) {

        logger.log(Level.WARNING,

                   elements[i].getMethodName());

    }

}

<!--[if !supportLists]-->9.       <!--[endif]-->Creating Exception Class

<!--[if !supportLists]-->1)      <!--[endif]-->Do you need an exception type that isn't represented by those in the Java platform?

<!--[if !supportLists]-->2)      <!--[endif]-->Would it help users if they could differentiate your exceptions from those thrown by classes written by other vendors?

<!--[if !supportLists]-->3)      <!--[endif]-->Does your code throw more than one related exception?

<!--[if !supportLists]-->4)      <!--[endif]-->If you use someone else's exceptions, will users have access to those exceptions? A similar question is, should your package be independent and self-containe


 

Choosing a Superclass

Any Exception subclass can be used as the parent class of LinkedListException. However, a quick perusal of those subclasses shows that they are inappropriate because they are either too specialized or completely unrelated to LinkedListException. Therefore, the parent class ofLinkedListException should be Exception.

Most applets and applications you write will throw objects that are Exceptions. Errors are normally used for serious, hard errors in the system, such as those that prevent the JVM from running.


Note: For readable code, it's good practice to append the string Exception to the names of all classes that inherit (directly or indirectly) from the Exception class. Eg, NoneFoundException

 

 

 

Errors and runtime exceptions are collectively known as unchecked exceptions.


 

<!--[if !supportLists]-->10.   <!--[endif]-->Advantage of Exception

 

<!--[if !supportLists]-->1)      <!--[endif]-->Separating Error-Handling Code from "Regular" Code

<!--[if !supportLists]-->2)      <!--[endif]-->Propagating Errors Up the Call Stack

<!--[if !supportLists]-->3)      <!--[endif]-->Grouping and Differentiating Error Types

Because all exceptions thrown within a program are objects, the grouping or categorizing of exceptions is a natural outcome of the class hierarchy. An example of a group of related exception classes in the Java platform are those defined in java.io  IOException and its descendants. IOException is the most general and represents any type of error that can occur when performing I/O. Its descendants represent more specific errors. For example,FileNotFoundException means that a file could not be located on disk.

 

                catch (Exception e) {    //A (too) general exception handler

                      ...

                }   This handler could handle any Exception with the handler here

 

 

<!--[if !supportLists]-->11.   <!--[endif]-->Exercises

 

<!--[if !supportLists]-->1)      <!--[endif]--> 

try {

 

} catch (Exception e) {

  

} catch (ArithmeticException a) {

   

}

Answer: This first handler catches exceptions of type Exception; therefore, it catches any exception, includingArithmeticException. The second handler could never be reached. This code will not compile.

 

2)   Question: Match each situation in the first list with an item in the second list.

int[] A; 
A[0] = 0;

The JVM starts running your program, but the JVM can't find the Java platform classes. (The Java platform classes reside in classes.zip or rt.jar.)

A program is reading a stream and reaches the end of stream marker.

Before closing the stream and after reaching the end of stream marker, a program tries to read the stream again.

__error

__checked exception

__compile error

__no exception

Answer:

3 (compile error). The array is not initialized and will not compile.

1 (error).

4 (no exception). When you read a stream, you expect there to be an end of stream marker. You should use exceptions to catch unexpected behavior in your program.

2 (checked exception).

<!--[if !supportLists]-->2)      <!--[endif]--> 

你可能感兴趣的:(java,exception)