概述
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 (see the next figure).
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.
总结:从文中可以了解异常如何捕捉,捕捉后,如果抛出异常,以及如何自定义自己的异常。
最后
以上就是任性摩托为你收集整理的重温Java经典教程(The Java™ Tutorials)第二篇-异常What Is an Exception?(什么是异常)的全部内容,希望文章能够帮你解决重温Java经典教程(The Java™ Tutorials)第二篇-异常What Is an Exception?(什么是异常)所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复