重溫Java經典教程(The Java™ Tutorials)第二篇-異常
What Is an Exception?(什麼是異常)
The term exception is shorthand for the phrase "exceptional event."
總結:當錯誤產生時,會產生異常物件,並交給執行時系統處理(整個過程稱作丟擲一個異常),然後執行時系統從call stack(呼叫堆疊)找到發生異常的方法,並看這個方法有沒有處理機制。(搜尋異常處理器)
Definition: An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.
When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception
After a method throws an exception, the runtime system attempts to find something to handle it. 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
The call stack.(呼叫堆疊圖片說明)
The runtime system searches the call stack for a method that contains a block of code that can handle the exception. This block of code is called an exception handler. The search begins with the method in which the error occurred and proceeds through the call stack in the reverse order in which the methods were called. When an appropriate handler is found, the runtime system passes the exception to the handler. An exception handler is considered appropriate if the type of the exception object thrown matches the type that can be handled by the handler.
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.
Searching the call stack for the exception handler.(為呼叫堆疊搜尋異常處理器)
Using exceptions to manage errors has some advantages over traditional error-management techniques. You can learn more in the Advantages of Exceptions section.
2018-12-13新增:
捕獲和處理異常(此處省略,瞭解try-catch-finally即可)
指定方法丟擲異常(先嚐試瞭解一下)
If the writeList
method doesn't catch the checked exceptions that can occur within it, the writeList
method must specify that it can throw these exceptions. Let's modify the original writeList
method to specify the exceptions it can throw instead of catching them. To remind you, here's the original version of the writeList
method that won't compile.
public void writeList() {
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();
}
To specify that writeList
can throw two exceptions, add a throws
clause to the method declaration for the writeList
method. The throws
clause comprises the throws
keyword followed by a comma-separated list of all the exceptions thrown by that method. The clause goes after the method name and argument list and before the brace that defines the scope of the method; here's an example.
public void writeList() throws IOException, IndexOutOfBoundsException {
Remember that IndexOutOfBoundsException
is an unchecked exception; including it in the throws
clause is not mandatory. You could just write the following.
public void writeList() throws IOException {
如何丟擲異常(How to Throw Exceptions)
Throwable Class and Its Subclasses
The objects that inherit from the Throwable
class include direct descendants (objects that inherit directly from the Throwable
class) and indirect descendants (objects that inherit from children or grandchildren of the Throwable
class). The figure belowillustrates the class hierarchy of the Throwable
class and its most significant subclasses. As you can see, Throwable
has two direct descendants: Error
and Exception
.
The Throwable class.
Error Class
When a dynamic linking failure or other hard failure in the Java virtual machine occurs, the virtual machine throws an Error
. Simple programs typically do not catch or throw Error
s.
Exception Class
Most programs throw and catch objects that derive from the Exception
class. An Exception
indicates that a problem occurred, but it is not a serious system problem. Most programs you write will throw and catch Exception
s as opposed to Error
s.
The Java platform defines the many descendants of the Exception
class. These descendants indicate various types of exceptions that can occur. For example, IllegalAccessException
signals that a particular method could not be found, and NegativeArraySizeException
indicates that a program attempted to create an array with a negative size.
One Exception
subclass, RuntimeException
, is reserved for exceptions that indicate incorrect use of an API. An example of a runtime exception is NullPointerException
, which occurs when a method tries to access a member of an object through a null
reference. The section Unchecked Exceptions — The Controversy discusses why most applications shouldn't throw runtime exceptions or subclass RuntimeException
.
Creating Exception Classes
An Example
Suppose you are writing a linked list class. The class supports the following methods, among others:
objectAt(int n)
— Returns the object in then
th position in the list. Throws an exception if the argument is less than 0 or more than the number of objects currently in the list.firstObject()
— Returns the first object in the list. Throws an exception if the list contains no objects.indexOf(Object o)
— Searches the list for the specifiedObject
and returns its position in the list. Throws an exception if the object passed into the method is not in the list.
The linked list class can throw multiple exceptions, and it would be convenient to be able to catch all exceptions thrown by the linked list with one exception handler. Also, if you plan to distribute your linked list in a package, all related code should be packaged together. Thus, the linked list should provide its own set of exception classes.
The next figure illustrates one possible class hierarchy for the exceptions thrown by the linked list.
Example exception class hierarchy.
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 of LinkedListException
should be Exception
.
Most applets and applications you write will throw objects that are Exception
s. Error
s are normally used for serious, hard errors in the system, such as those that prevent the JVM from running.