JHTP小结_第十一章_深入理解异常(Exception Handling)

不知道为什么,这章的内容看起来很吃力。

本来以为自己的英语还不错,前面的几章看的挺顺溜,难道是因为前面几章的知识已经比较熟悉的缘故?大笑->哭


Summary

Section 11.1Introduction

• An exception is anindication of a problem that occurs during a program’s execution.

• Exception handlingenables programmers to create applications that can resolve exceptions.

Section 11.2Example: Divide by Zero without Exception Handling

• Exceptions are thrown(p. 443) when a method detects a problem and is unable to handle it.

• An exception’s stacktrace (p. 444) includes the name of the exception in a message that indicates the problem that occurredand the complete method-call stack at the time the exception occurred.

• The point in theprogram at which an exception occurs is called the throw point (p. 445).

Section 11.3Example: Handling ArithmeticExceptions and InputMismatchExceptions

• A try block (p.447) encloses code that might throw an exception and codethat should not execute if that exception occurs.

• Exceptions may surfacethrough explicitly mentioned code in a try block,through calls to other methods or even throughdeeply nested method calls initiated by code in the try block.

• A catch block (p.448) begins with keyword catch and an exception parameter followed by a block of code that handles theexception. This code executes when the try block detectsthe exception.

• At least one catch block or a finally block (p.448) must immediately follow the try block.

• A catch blockspecifies in parentheses an exception parameter identifying the exception typeto handle. The parameter’sname enables the catch block to interact with a caught exception object.

• An uncaught exception(p. 449) is an exception that occurs for which there are no matching catch blocks. Anuncaught exception will cause a program to terminate early if that programcontains only one thread.Otherwise, only the thread in which the exception occurred will terminate.

The rest of the programwill run but possibly with adverse results.

• Multi-catch (p. 449)enables you to catch multiple exception types in a single catch handler and perform the same task foreach type of exception. The syntax for a multi-catch is:

catch (Type1 | Type2 | Type3 e)

• Each exception type isseparated from the next with a vertical bar (|).

• If an exception occursin a try block, the try block terminates immediately and program control transfers to the first catch block with aparameter type that matches the thrown exception’s type.

• After an exception ishandled, program control does not return to the throw point, because the try block has expired.This is known as the termination model of exception handling (p. 449).

• If there are multiplematching catch blocks when an exception occurs, only the first is executed.

• A throws clause (p.450) specifies a comma-separated list of exceptions that the method might throw, and appears afterthe method’s parameter list and before the method body.

Section 11.4 Whento Use Exception Handling

• Exception handlingprocesses synchronous errors (p. 451), which occur when a statement executes.

• Exception handling isnot designed to process problems associated with asynchronous events (p. 451), which occur inparallel with, and independent of, the program’s flow of control.

Section 11.5 JavaException Hierarchy

• All Java exceptionclasses inherit directly or indirectly from class Exception.

• Programmers can extendthe Java exception hierarchy with their own exception classes.

• Class Throwable is thesuperclass of class Exception and is therefore also the superclass of all exceptions. Only Throwable objects canbe used with the exception-handling mechanism.

• Class Throwable (p. 451) hastwo subclasses: Exception and Error.

• Class Exception and itssubclasses represent problems that could occur in a Java program and be caught by the application.

• Class Error and itssubclasses represent problems that could happen in the Java runtime system.

Errors happeninfrequently and typically should not be caught by an application.

• Java distinguishesbetween two categories of exceptions (p. 452): checked and unchecked.

• The Java compiler doesnot check to determine if an unchecked exception is caught or declared.

Unchecked exceptionstypically can be prevented by proper coding.

• Subclasses of RuntimeExceptionrepresent unchecked exceptions. All exception types that inherit from class Exception but not from RuntimeException(p. 452) are checked.

• If a catch block iswritten to catch exception objects of a superclass type, it can also catch allobjects of that class’ssubclasses. This allows for polymorphic processing of related exceptions.

Section 11.6 finallyBlock

• Programs that obtaincertain types of resources must return them to the system to avoid so-called resource leaks (p. 454).Resource-release code typically is placed in a finally block (p.454).

• The finally block isoptional. If it’s present, it’s placed after the last catch block.

• The finally block willexecute whether or not an exception is thrown in the corresponding try block or any of itscorresponding catch blocks.

• If an exception cannotbe caught by one of that try block’s associated catch handlers,control proceeds to the finally block. Thenthe exception is passed to the next outer try block.

• If a catch block throwsan exception, the finally block still executes. Then the exception is passed to the next outer try block.

• A throw statement (p.457) can throw any Throwable object.

• Exceptions are rethrown(p. 458) when a catch block, upon receiving an exception, decides either that it cannot processthat exception or that it can only partially process it. Rethrowing an exception defers theexception handling (or perhaps a portion of it) to another catch block.

• When a rethrow occurs,the next enclosing try block detects the rethrown exception, and that try block’s catch blocksattempt to handle it.

Section 11.7 StackUnwinding and Obtaining Information from an Exception Object

• When an exception isthrown but not caught in a particular scope, the method-call stack is unwound, and an attempt is made tocatch the exception in the next outer try statement.

• Class Throwable offers a printStackTracemethod that prints the method-call stack. Often, this is helpful in testing anddebugging.

• Class Throwable also providesa getStackTrace method that obtains the same stack-trace information that’s printed by printStackTrace(p. 461).

• Class Throwable’s getMessagemethod (p. 461) returns the descriptive string stored in anexception.

• Method getStackTrace(p. 461) obtains the stack-trace information as an array of StackTrace- Element objects. EachStackTraceElement represents one methodcall on the method-call stack.

StackTraceElementmethods (p. 461) getClassName, getFileName, getLineNumberand get-MethodName get the classname, filename, line number and method name, respectively.

Section 11.8Chained Exceptions

• Chained exceptions (p.462) enable an exception object to maintain the complete stack-traceinformation, including informationabout previous exceptions that caused the current exception.

Section 11.9Declaring New Exception Types

• A new exception classmust extend an existing exception class to ensure that the class can be used with theexception-handling mechanism.

Section 11.10Preconditions and Postconditions

• A method’s precondition(p. 465) must be true when the method is invoked.

• A method’spostcondition (p. 465) is true after the method successfully returns.

• When designing your ownmethods, you should state the preconditions and postconditions in a comment before the methoddeclaration.

Section 11.11Assertions

• Assertions (p. 465)help catch potential bugs and identify possible logic errors.

• The assert statement (p.466) allows for validating assertions programmatically.

• To enable assertions atruntime, use the -ea switch when running the java command.

Section 11.12 try-with-Resources:Automatic Resource Deallocation

• The try-with-resourcesstatement (p. 467) simplifies writing code in which you obtain a resource, use it in a try block andrelease the resource in a corresponding finally block.Instead, you allocate the resource in theparentheses following the try keyword and use the resource in the try block; then the statementimplicitly calls the resource’s close method at the end of the try block.

• Each resource must bean object of a class that implements the AutoCloseable interface (p. 467)—such a class hasa close method.

• You can allocatemultiple resources in the parentheses following try by separatingthem with a semicolon (;).


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值