Java Exception Study

阅读更多

Java Exception

1.       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)

 

2.       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.


 

 

3.       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.

 

4.       Three kinds of exception

1)      Checked Exception

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

2)      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.

3)      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.

 

5.       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;

}

 

6.       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();

  }

}

 

7.       Throw Exceptions

throw someThrowableObject;

 

 

 

 

 

 

8.       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());

    }

}

9.       Creating Exception Class

1)      Do you need an exception type that isn't represented by those in the Java platform?

2)      Would it help users if they could differentiate your exceptions from those thrown by classes written by other vendors?

3)      Does your code throw more than one related exception?

4)      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.


 

10.   Advantage of Exception

 

1)      Separating Error-Handling Code from "Regular" Code

2)      Propagating Errors Up the Call Stack

3)      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

 

 

11.   Exercises

 

1)       

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).

2)       

你可能感兴趣的:(Java Exception Study)