<!--[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]--><!--[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]--><!--[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]--><!--[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() + "()");
}
}
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]-->
发表评论
-
Classloader
2011-11-22 14:09 753The class loader: BootStrap c ... -
JUnit Knowledges
2011-10-25 23:09 758mock objects: http://bigwhite. ... -
Java跨平台程序设计规则
2011-09-20 12:38 951不是说所有的Java程序都具有Java跨平台的特性,事实上,相 ... -
Servlet - life cycle and listener events
2011-08-25 15:56 836import database.BookDBAO; ... -
Common Gateway Interface
2011-08-25 15:20 1387A web server that supports ... -
什么时候使用属性或者元素(Designing XML document)
2011-08-19 11:34 1008Properties 是平面结构,想要表达结构复杂的信息有一定 ... -
Java - Generic
2011-07-19 12:35 725Generics <!--[if !suppor ... -
面向对象的设计的四个主要原则
2011-07-11 14:22 13571. ISP (Interface Segregation ... -
Design Pattern
2011-07-11 11:52 654Mediator 一、引子 中介在现实 生活中并 ... -
Java Generic, Association, Composition, Aggregate
2011-07-05 16:20 1148UML中依赖泛化关联实现聚合组合的Java实现 ... -
ETL
2011-06-30 11:36 851ETL 对于数据仓库以及ETL的知识,我基本上是个 ... -
Java Collection Frameworks 学习
2011-06-30 11:17 692Java 集合总结 <!--[if !su ... -
Java Clone
2011-06-29 16:07 810Clone interface: 如果一个实现了Cl ... -
Credit Card 的工具类
2010-05-10 15:24 878这是一个非常有用的工具类用于验证credit card, 是a ... -
实例化抽象类时实现抽象类里的抽象方法
2010-04-16 09:18 1004EccTrxCmd logWSCall = new EccTr ... -
Java reflect
2010-03-09 16:21 813【转】Java反射经典实例 Java Reflection C ...
相关推荐
### SCJP6 Sun Certified Programmer for Java 6 Study Guide (Exam 310-065) #### 1. Declarations and Access Control In the first chapter, the focus is on understanding declarations and access control ...
在Android系统中,应用程序主要基于Java运行时环境进行开发,但也有不少部分是通过Native代码(如C/C++)实现的,这些Native代码通常运行在较低级别的操作系统层面上。当Native代码出现错误时,就会触发Native ...
### Oracle Certified Associate, Java SE 7 Programmer Study Guide #### 知识点概览 本学习指南旨在帮助考生准备Oracle Certified Associate (OCA) Java SE 7 Programmer I 认证考试(代码1Z0-803)。该指南覆盖...
You’ll enjoy the Deitels’ classic treatment of object-oriented programming and the OOD/UML ATM case study, including a complete Java implementation. When you’re finished, you’ll have everything ...
【Java编程语言基础】 Java是一种广泛使用的面向对象的编程语言,由Sun Microsystems(现已被Oracle公司收购)在1995年推出。它的设计目标是具有简单性、面向对象、健壮性、安全性、可移植性等特性。Java程序可以在...
You’ll enjoy the Deitels’ classic treatment of object-oriented programming and the object-oriented design ATM case study, including a complete Java implementation. When you’re finished, you’ll ...
} catch (ArithmeticException e) { System.out.println("除数不能为零"); } finally { // 清理资源 } ``` 【集合框架】 Java集合框架是一组接口和类,它们提供了存储和操作对象的通用数据结构。主要的接口有`...
} catch (Exception e) { e.printStackTrace(); } } } ``` 本教程通过一系列的上机实践,旨在帮助你掌握Java面向对象编程的基础知识,包括类、对象、继承、接口、封装,以及如何使用JDBC进行数据库操作。通过...
Java程序设计基础篇是入门Java编程的重要阶段,涵盖了语言的基础语法、数据类型、控制结构、类与对象等核心概念。这份文档集包含了该部分的学习者可能会遇到的问题解答,旨在为初学者提供指导和帮助。 首先,Java是...
void study() { // 学习的逻辑 } void communicate() { // 交流的逻辑 } } ``` 二、封装 封装是面向对象的三大特性之一,它隐藏了对象的内部实现细节,仅通过公共接口与外界交互。在Java中,我们可以通过...
Java是一种广泛使用的面向对象的编程语言,以其跨平台性、高效性和丰富的类库而闻名。在Java的基础操作中,我们通常会接触到许多核心概念和技术,包括数据类型、变量、控制结构、类与对象、异常处理等。下面我们将...
- **Exception Handling:** Understand exception handling mechanisms in Java. - **File Handling:** Learn about file input/output operations. - **Concurrency:** Explore concurrency concepts and ...
} catch (Exception e) { ... } finally { ... }`。异常是程序运行时的错误,捕获异常可以帮助我们编写健壮的代码。 10. **输入输出流**:Java的IO流系统允许程序读取或写入数据。例如,使用`FileInputStream`和`...
7. **异常处理(Exception Handling)**:Java提供了强大的异常处理机制,允许程序员捕获并处理运行时错误。使用`try-catch-finally`块来捕获和处理异常。 8. **集合框架(Collection Framework)**:Java集合框架...
### Java练习题知识点详解 #### 1. 冒泡排序法 **知识点**: 冒泡排序是一种简单的排序算法。它重复地走访过要排序的数列,一次比较两个元素,如果他们的顺序错误就把他们交换过来。走访数列的工作是重复地进行直到...
在"study_pro"这个压缩包中,可能包含了上述各个知识点的实例代码,通过学习和实践这些代码,你可以深入理解Java基础,并逐步提升编程技能。对于初学者来说,从简单的控制流开始,逐步接触类和对象的概念,然后学习...