DbC vs. Exception

Similar documents
chp6.ppt

<4D F736F F D C4EAC0EDB9A4C0E04142BCB6D4C4B6C1C5D0B6CFC0FDCCE2BEABD1A15F325F2E646F63>

4. 每 组 学 生 将 写 有 习 语 和 含 义 的 两 组 卡 片 分 别 洗 牌, 将 顺 序 打 乱, 然 后 将 两 组 卡 片 反 面 朝 上 置 于 课 桌 上 5. 学 生 依 次 从 两 组 卡 片 中 各 抽 取 一 张, 展 示 给 小 组 成 员, 并 大 声 朗 读 卡

Fun Time (1) What happens in memory? 1 i n t i ; 2 s h o r t j ; 3 double k ; 4 char c = a ; 5 i = 3; j = 2; 6 k = i j ; H.-T. Lin (NTU CSIE) Referenc

Lorem ipsum dolor sit amet, consectetuer adipiscing elit

Microsoft Word - TIP006SCH Uni-edit Writing Tip - Presentperfecttenseandpasttenseinyourintroduction readytopublish

Microsoft Word - 11月電子報1130.doc

2/80 2

Microsoft Word doc

C o n t e n t s Acceptance Allow Love Apologize Archangel Metatron Archangel Michael Ask for

BUILDING THE BEST MARKETING BUDGET FOR TODAY S B2B ENVIRONMENT For most marketers, budgeting and planning for the next year is a substantial undertaki


參 加 第 二 次 pesta 的 我, 在 是 次 交 流 營 上 除 了, 與 兩 年 沒 有 見 面 的 朋 友 再 次 相 聚, 加 深 友 誼 外, 更 獲 得 與 上 屆 不 同 的 體 驗 和 經 歴 比 較 起 香 港 和 馬 來 西 亞 的 活 動 模 式, 確 是 有 不 同 特

Microsoft Word - 第四組心得.doc

<4D F736F F D205F FB942A5CEA668B443C5E9BB73A740B5D8A4E5B8C9A552B1D0A7F75FA6BFB1A4ACFC2E646F63>


Lorem ipsum dolor sit amet, consectetuer adipiscing elit

BC04 Module_antenna__ doc

Windows XP

[ 13 年 12 月 06 日, 下 午 6 点 24 分 ] Intel Hosts 新 加 入 的 同 学 们, 快 去 听 听 在 线 宣 讲 会 哦, 同 时 完 成 页 面 下 方 有 奖 调 查, 就 有 资 格 参 与 大 奖 抽 取 啦! [ 13 年 12 月 06 日, 下 午

國立中山大學學位論文典藏

2-7.FIT)

可 愛 的 動 物 小 五 雷 雅 理 第 一 次 小 六 甲 黃 駿 朗 今 年 暑 假 發 生 了 一 件 令 人 非 常 難 忘 的 事 情, 我 第 一 次 參 加 宿 營, 離 開 父 母, 自 己 照 顧 自 己, 出 發 前, 我 的 心 情 十 分 緊 張 當 到 達 目 的 地 後

高中英文科教師甄試心得

99 學年度班群總介紹 第 370 期 班群總導 陳怡靜 G45 班群總導 陳怡靜(河馬) A 家 惠如 家浩 T 格 宜蓁 小 霖 怡 家 M 璇 均 蓁 雴 家 數學領域 珈玲 國燈 英領域 Kent

The Development of Color Constancy and Calibration System

Preface This guide is intended to standardize the use of the WeChat brand and ensure the brand's integrity and consistency. The guide applies to all d

硕 士 学 位 论 文 论 文 题 目 : 北 岛 诗 歌 创 作 的 双 重 困 境 专 业 名 称 : 中 国 现 当 代 文 学 研 究 方 向 : 中 国 新 诗 研 究 论 文 作 者 : 奚 荣 荣 指 导 老 师 : 姜 玉 琴 2014 年 12 月

1.ai

epub83-1

2005 5,,,,,,,,,,,,,,,,, , , 2174, 7014 %, % 4, 1961, ,30, 30,, 4,1976,627,,,,, 3 (1993,12 ),, 2

第六章

Microsoft Word - template.doc

A Community Guide to Environmental Health

Microsoft Word - 武術合併

Important Notice SUNPLUS TECHNOLOGY CO. reserves the right to change this documentation without prior notice. Information provided by SUNPLUS TECHNOLO

untitled

UTI (Urinary Tract Infection) - Traditional Chinese

穨control.PDF

Microsoft PowerPoint _代工實例-1

软件测试(TA07)第一学期考试

Some experiences in working with Madagascar: installa7on & development Tengfei Wang, Peng Zou Tongji university

3.1 num = 3 ch = 'C' 2

Microsoft PowerPoint - STU_EC_Ch08.ppt

中國文化大學政治學研究所

< F5FB77CB6BCBD672028B0B6A46AABE4B751A874A643295F5FB8D5C5AA28A668ADB6292E706466>

蔡 氏 族 譜 序 2

ENGG1410-F Tutorial 6

Microsoft Word - Final Exam Review Packet.docx

目 錄 實 施 計 畫 1 專 題 演 講 因 應 十 二 年 國 民 基 本 教 育 課 程 綱 要 學 校 本 位 課 程 的 整 體 布 局 A-1 推 動 十 二 年 國 民 基 本 教 育 課 程 綱 要 相 關 配 套 措 施 A-10 分 組 研 討 法 規 研 修 B-1 課 程 教


TA-research-stats.key

東莞工商總會劉百樂中學

莊 子

星河33期.FIT)

K301Q-D VRT中英文说明书141009

(Microsoft Word - 10\246~\253\327\262\304\244@\264\301\256\325\260T_Version4)

<4D F736F F D203033BDD7A16DA576B04FA145A4ADABD2A5BBACF6A16EADBAB6C0ABD2A4A7B74EB8712E646F63>

encourages children to develop rich emotions through close contact with surrounding nature. It also cultivates a foundation for children s balanced de

2. 佔 中 對 香 港 帶 來 以 下 影 響 : 正 面 影 響 - 喚 起 市 民 對 人 權 及 ( 專 制 ) 管 治 的 關 注 和 討 論 o 香 港 市 民 總 不 能 一 味 認 命, 接 受 以 後 受 制 於 中 央, 沒 有 機 會 選 出 心 中 的 理 想 特 首 o 一

LH_Series_Rev2014.pdf

穨6街舞對抗中正紀念堂_林伯勳張金鶚_.PDF

PowerPoint Presentation

(baking powder) 1 ( ) ( ) 1 10g g (two level design, D-optimal) 32 1/2 fraction Two Level Fractional Factorial Design D-Optimal D

2015 Chinese FL Written examination


UDC The Policy Risk and Prevention in Chinese Securities Market

前 言 一 場 交 換 學 生 的 夢, 夢 想 不 只 是 敢 夢, 而 是 也 要 敢 去 實 踐 為 期 一 年 的 交 換 學 生 生 涯, 說 長 不 長, 說 短 不 短 再 長 的 路, 一 步 步 也 能 走 完 ; 再 短 的 路, 不 踏 出 起 步 就 無 法 到 達 這 次

考試學刊第10期-內文.indd

<4D F736F F D203338B4C12D42A448A4E5C3C0B34EC3FE2DAB65ABE1>

東吳大學

untitled

声 明 本 人 郑 重 声 明 : 此 处 所 提 交 的 硕 士 学 位 论 文 基 于 等 级 工 鉴 定 的 远 程 考 试 系 统 客 户 端 开 发 与 实 现, 是 本 人 在 中 国 科 学 技 术 大 学 攻 读 硕 士 学 位 期 间, 在 导 师 指 导 下 进 行 的 研 究

A VALIDATION STUDY OF THE ACHIEVEMENT TEST OF TEACHING CHINESE AS THE SECOND LANGUAGE by Chen Wei A Thesis Submitted to the Graduate School and Colleg

Logitech Wireless Combo MK45 English

Microsoft PowerPoint - AWOL - Acrobat Windows Outlook.ppt [Compatibility Mode]

準 備 第 1~2 週 服 務 第 3~15 週 反 省 第 16~17 週 慶 賀 第 18 週 六 合 作 機 構 協 力 單 位 合 作 協 議 書 : 已 簽 及 附 影 本 乙 份 未 簽, 核 准 之 後 補 送 機 構 名 稱 / 聯 絡 人 台 中 市 青 年 志 工 中 心 財 團

untitled

Microsoft Word - 十月號.doc

川 外 250 人, 上 外 222 人, 广 外 209 人, 西 外 195 人, 北 外 168 人, 中 南 大 学 135 人, 西 南 大 学 120 人, 湖 南 大 学 115 人, 天 外 110 人, 大 连 外 国 语 学 院 110 人, 上 海 外 事 学 院 110 人,

南華大學數位論文

: : : : : ISBN / C53:H : 19.50

<4D F736F F F696E74202D20C8EDBCFEBCDCB9B9CAA6D1D0D0DEBDB2D7F92E707074>

1 引言

HC50246_2009

OA-253_H1~H4_OL.ai

9330.doc

<4D F736F F D20D0ECB7C9D4C6A3A8C5C5B0E6A3A92E646F63>

1. 請 先 檢 查 包 裝 內 容 物 AC750 多 模 式 無 線 分 享 器 安 裝 指 南 安 裝 指 南 CD 光 碟 BR-6208AC 電 源 供 應 器 網 路 線 2. 將 設 備 接 上 電 源, 即 可 使 用 智 慧 型 無 線 裝 置 進 行 設 定 A. 接 上 電 源

Microsoft PowerPoint - NCBA_Cattlemens_College_Darrh_B

A dissertation for Master s degree Metro Indoor Coverage Systems Analysis And Design Author s Name: Sheng Hailiang speciality: Supervisor:Prof.Li Hui,

2015年4月11日雅思阅读预测机经(新东方版)

1: public class MyOutputStream implements AutoCloseable { 3: public void close() throws IOException { 4: throw new IOException(); 5: } 6:

Untitiled

國立桃園高中96學年度新生始業輔導新生手冊目錄

hks298cover&back

1505.indd

IP Access Lists IP Access Lists IP Access Lists

TX-NR3030_BAS_Cs_ indd

Microsoft Word 國企國貿.doc

Transcription:

DbC vs. Exception 契约式设计 vs. 异常

Exception 问题 何谓 异常 (Exception)? 一种情况要 异常 到什么程度才算 异常? 为什么要引入异常处理机制? Robustness? Readability? 如何进行异常处理? Mandatory or Optional 不同的认识, 不同的答案 Java/C++/C# Eiffel

Java Exception Mechanisms 3 Java 对 Exception 的界定较宽 因而需认真区分不同类型的 Exceptions Java 的 Exception 机制回顾 try/catch/finally throw Exceptions 自定义 Exceptions Java Exception 与 Design by Contract Exception 的转换

What are Exceptions? Many exceptional things can happen during the running of a program, e.g.: User mis-types input Web page not available Array index out of bounds Method called on a null object Out of memory File not found Divide by zero Bug in the actual language implementation Exceptions are unexpected conditions in programs. checked unchecked sys errors 4

We can distinguish 3 categories: checked exceptions Problems to do with the program's interaction with the world. The world is unpredictable, so we would expect these things to happen in production code, and so need to handle them. The World Checked Exceptions Program System 5

We can distinguish 3 categories: checked exceptions Problems to do with the program's interaction with the world. unchecked exceptions Problems within the program itself (i.e. violations of the contract, or bugs). The World These should be removed by testing, and not occur in production code. Checked Exceptions Unchecked Exceptions Program System 6

We can distinguish 3 categories: checked exceptions Problems to do with the program's interaction with the world. unchecked exceptions Problems within the program itself (i.e. violations of the contract, or bugs). system errors Problems with the underlying system. These are outside our control. Unchecked Exceptions The World Program System Checked Exceptions System Errors 7

Checked vs Unchecked Exceptions an important distinction, which the Java Exception class hierarchy does make, but in a rather confusing way 8

Checked vs Unchecked Exceptions it's normal to let these just crash the program so we can debug it. we would normally check for these, and deal with them when they occur. Unchecked Exceptions The World Program System Checked Exceptions System Errors Exception handling is the business of handling these things appropriately. 9

Exception Hierarchy in Java Throwable Error Exception RuntimeException... RuntimeException The World Checked Exceptions Exception RuntimeException Unchecked Exceptions Program System System Errors Error 10

What do we want of exceptions? Ideally, a language (and its implementation) should: Restrict the set of possible exceptions to reasonable ones e.g. no pointers to deallocated memory 11

What do we want of exceptions? Ideally, a language (and its implementation) should: Restrict the set of possible exceptions to reasonable ones Indicate where they happened, and distinguish between them and not map them all to bus error etc. 12

What do we want of exceptions? Ideally, a language (and its implementation) should: Restrict the set of possible exceptions to reasonable ones Indicate where they happened, and distinguish between them Allow exceptions to be dealt with in a different place in the code from where they occur so normal case code can be written cleanly without having to worry about them 13

What do we want of exceptions? Ideally, a language (and its implementation) should: Restrict the set of possible exceptions to reasonable ones Indicate where they happened, and distinguish between them Allow exceptions to be dealt with in a different place in the code from where they occur so we throw exceptions where they occur, and catch them where we want to deal with them. 14 Ideally, we don't want non-fatal exceptions to be thrown too far this breaks up the modularity of the program and makes it hard to reason about.

Exceptions in Java a reminder In Java, the basic exception handling construct is to: try a block of code which normally executes ok catch any exceptions that it generates, and finally do anything we want to do irrespective of what happened before. If a thrown exception is not caught, it propagates out to the caller and so on until main. If it is never caught, it terminates the program. If a method can generate (checked) exceptions but does not handle them, it has to explicitly declare that it throws them so that clients know what to expect. 15

The Throwable Class Hierarchy The standard API defines many different exception types basic ones in java.lang others in other packages, especially java.io Throwable Top level class is not Exception but Throwable. Error Exception RuntimeException... 16

Throwable Error Exception Problems with the underlying Java platform, e.g. VirtualMachineError. RuntimeException... User code should never explicitly generate Errors. This is not always followed in the Java API, and you may occasionally need to say catch (Throwable e) to detect some bizarre error condition 17

Throwable Error Exception Problems with the underlying Java platform, e.g. VirtualMachineError. RuntimeException... User code should never explicitly generate Errors. In general, you want to catch specific sorts of (checked) exceptions, and saying catch (Exception e) is bad style. never mind Throwable! 18

Throwable Error Exception RuntimeException... Unchecked exceptions are subclasses of RuntimeException It would be much clearer if this was called UncheckedException These include our old friends NullPointerException and ArrayIndexOutOfBoundsException. Virtually any method can in principle throw one or more of these, so there's no requirement to declare them in throws clauses. 19

Throwable Error Exception All other exceptions are checked exceptions RuntimeException... It would be nice if there was a class CheckedException. 20

Throwable Error Exception All other exceptions are checked exceptions RuntimeException... The most common ones are IOExceptions such as FileNotFoundException. If you write code which can throw one of these, you must either catch it or declare that the method throws it. The compiler goes to enormous lengths to enforce this, and related constraints, e.g. that all overridden versions of a method have consistent throws clauses. 21

Exception Handling and DbC Exceptions are about dealing with things going wrong at runtime. DbC is about statically defining the conditions under which code is supposed to operate. (The two are nicely complementary.) Unchecked exceptions are what happens when the contract is broken Checked exceptions are expected so are not contract violations. to happen from time to time e.g. if a precondition that an array has at least one element is broken, an ArrayIndexOutOfBoundsException will probably occur. 22

So if we're going to use DbC,we ought to structure our code into: code which deals with The World Methods doing this will have no (or weak) preconditions, and will deal with problems via exception handling. 23

So if we're going to use DbC,we ought to structure our code into: code which deals with The World code which is insulated from The World. This can have strong preconditions and won't throw exceptions (apart from unchecked ones during debugging). 24

So if we're going to use DbC,we ought to structure our code into: code which deals with The World code which is insulated from The World. E.g. an application involving form-filling should have code which validates the user input for type-correctness etc. code which relies on the input being correct to process it If these two sorts of operations are mixed together, the application will probably be harder to maintain and more error-prone. 25

Converting Exceptions Good OO design decouples things. E.g. in most patterns there's a Client class which delegates operations to some black box in the pattern. Client op Black box some application-specific code some application-independent library 26

Converting Exceptions Good OO design decouples things. E.g. in most patterns there's a Client class which delegates operations to some black box in the pattern. Client op Black box some application-specific code some application-independent library What happens if the black box throws a (checked) exception? 27

Converting Exceptions Good OO design decouples things. E.g. in most patterns there's a Client class which delegates operations to some black box in the pattern. Client op Black box some application-specific code may have its own exception types, but they need to be applicationspecific. some application-independent library exceptions thrown from within the library will be applicationindependent. 28

try {... obj.delegateop(...);... } catch (ApplicationIndependentException e){ throw new ApplicationSpecificException(e); } ApplicationSpecificException will therefore have a constructor which takes an ApplicationIndependentException extracts the relevant information and re-casts it in application-specific terms. 29

Example Consider a compiler for an oo language In such a compiler, it's useful to have an explicit representation of the inheritance hierarchy of the source program as a tree (or graph). 30

Example Consider a compiler for an oo language which has an application-independent Hierarchy class which represents a hierarchy of arbitrary key-value pairs. The key is the class name and the value is the definition of the class. 31

Example Consider a compiler for an oo language which has an application-independent Hierarchy class which represents a hierarchy of arbitrary key-value pairs. If something goes wrong in building or using a Hierarchy an InvalidHierarchyException is thrown. e.g. a node has no parent, or there's a cycle 32

33 Example Consider a compiler for an oo language which has an application-independent Hierarchy class which represents a hierarchy of arbitrary key-value pairs. If something goes wrong in building or using a Hierarchy an InvalidHierarchyException is thrown. If this occurs while the class hierarchy is being built, it means the user has mis-spelt a class name or whatever. The InvalidHierarchyExcetpion is converted to a (checked) IllegalInheritanceException resulting in a suitable error message being displayed to the user. If it happens later, an (unchecked) CompilerBrokenExpection is thrown instead, because it means there's a bug in the compiler.

Summary Exception handling is an important, highly integrated, part of the Java system, one of the Really Neat Things About Java. Unchecked exceptions routinely occur during debugging, and make that process much easier. By product shipping time, they should no longer occur. Checked exceptions happen when the program's interaction with the world departs from the normal case. Make sure you handle them appropriately. In particular, think hard about where to handle an exception, so as to simplify the normal-case code, but not to do the handling so far away that modularity is compromised. Application-independent exceptions need to be converted to application-specific ones. 34

Eiffel Exception 机制简介 35 Eiffel 观点 : 契约破坏才会有 Exception Eiffel Exception 机制的设计基于此观点

Basic Concepts 36 The need for exceptions arises when the contract is broken.

Basic Concepts 37 Exception: an undesirable event occurs during the execution of a routine as a result of the failure of some operation called by the routine.

The original strategy 38 r (...) is require do ensure end... op1 op2... opi... opn... Fails, triggering an exception in r (r is recipient of exception).

Causes of exceptions 39 Assertion violation Void call (x.f with no object attached to x) Operating system signal (arithmetic overflow, no more memory, interrupt...)

Handling exceptions properly 41 Safe exception handling principle: There are only two acceptable ways to react for the recipient of an exception: Failure (Organized Panic 合理组织的 恐慌 ): clean up the environment, terminate the call and report failure to the caller. Panic: making sure that the caller gets an exception Organized: restoring a consistent execution state Retrying: Try again, using a different strategy (or repeating the same strategy).

How not to do things? 42 (From an Ada textbook) sqrt (x: REAL) return REAL is begin exception if x < 0.0 then else end raise Negative; normal_square_root_computation; Give up and return to the caller as if everything was fine, although not when Negative => put ("Negative argument"); return; when others => end; -- sqrt

The call chain 43 r0 Routine call r1 r2 r3 r4

Exception mechanism 44 Two constructs: A routine may contain a rescue clause. A rescue clause may contain a retry instruction. A rescue clause that does not execute a retry leads to failure of the routine (this is the organized panic case). Failure Principle If an exception occurs in a routine without rescue clause it will cause the routine to fail, trigger an exception in its caller.

45 Transmitting over an unreliable line (1) Max_attempts: INTEGER is 100 attempt_transmission (message: STRING) is -- Transmit message in at most local do rescue -- Max_attempts attempts. failures: INTEGER unsafe_transmit (message) failures := failures + 1 if failures < Max_attempts then retry end end

46 Transmitting over an unreliable line (2) Max_attempts: INTEGER is 100 failed: BOOLEAN attempt_transmission (message: STRING) is -- Try to transmit message; -- if impossible in at most Max_attempts -- attempts, set failed to true. local failures: INTEGER do if failures < Max_attempts then unsafe_transmit (message) else failed := True end rescue failures := failures + 1 retry end

If no exception clause (1) 47 Absence of a rescue clause is equivalent, in first approximation, to an empty rescue clause: f (...) is do... end is an abbreviation for f (...) is do... rescue end -- Nothing here (empty instruction list) (This is a provisional rule; see next.)

The correctness of a class 48 create a.make ( ) S1 For every exported routine r: {INV and Prer} dor {Postr and INV} For every creation procedure cp: {Precp} docp {Postcp and INV} S2 S3 S4 a.f ( ) a.g ( ) a.f ( )

Exception correctness: A quiz 49 For the normal body: {INV and Prer} dor {Postr and INV} For the exception clause: {??? } rescuer {??? } Should it be lazy? Weakest? Strongest? The stronger the precond, the easier the job

Quiz answers 50 For the normal body: {INV and Prer} dor {Postr and INV} For the rescue clause: {True} rescuer {INV} For the retry-introducing rescue clause: {True} retryr {INV and Prer }

Separation of roles 51 Normal body: ensure the routine s contract; not directly to handle exceptions Rescue clause: handle exceptions, returning control to the body or (in the failure case) to the caller; not to ensure the contract.

If no exception clause (2) 52 Absence of a rescue clause is equivalent to a default rescue clause: f (...) is do... end is an abbreviation for f (...) is do... rescue end default_rescue The task of default_rescue is to restore the invariant.

For finer-grain exception handling 53 Use class EXCEPTIONS from the Kernel Library. Some features: exception (code of last exception that was triggered). assertion_violation, etc. raise ( exception_name )

小结 54 使用 Eiffel Exception 机制来构造 Robust 的软件 使用 Java/C++/C# Exception 机制来构造 Robust Correct Easy-to-Read

作业 55 解释 checked exception, unchecked exception 和 error 三者的定义以及使用的区别 从 DbC 的角度看,Java 方法声明中的 throws 子句反映了类 (supplier ) 和其使用者 (client) 之间的怎样的权利 / 义务关系?Java 子类若重定义父类中的方法, 其 throws 的异常有何限制? 用 DbC 的 Contract 继承原则解释这个限制 4 月 11 日晚上 24:00 前 提交至 OODClass@163.com 邮件附件以及主题命名形式, 第四次作业 - 学号 - 姓名.XXX

Java Exception 56 Java Exception 机制的不当使用 : 引自网络论坛 : http://www.chinaunix.net/forum/viewtopic.php?t=136123

1 OutputStreamWriter out =... 2 java.sql.connection conn =... 3 try { // ⑸ 4 Statement stat = conn.createstatement(); 5 ResultSet rs = stat.executequery( 6 "select uid, name from user"); 7 while (rs.next()) 8 { 9 out.println("id:" + rs.getstring("uid") // ⑹ 10 ", 姓名 :" + rs.getstring("name")); 11 } 12 conn.close(); // ⑶ 13 out.close(); 14 } 15 catch(exception ex) // ⑵ 16 { 17 ex.printstacktrace(); //⑴,⑷ 18 } 57

1 OutputStreamWriter out =... 2 java.sql.connection conn =... 3 try { // ⑸ 4 Statement stat = conn.createstatement(); 5 ResultSet rs = stat.executequery( 6 "select uid, name from user"); 7 while (rs.next()) 8 { 9 out.println("id:" + rs.getstring("uid") // ⑹ 10 ", 姓名 :" + rs.getstring("name")); 11 } 12 conn.close(); // ⑶ (1) 丢弃异常! 13 out.close(); 14 } 15 catch(exception ex) // ⑵ 16 { 17 ex.printstacktrace(); //⑴,⑷ 18 } 58

Anti-pattern 59 丢弃异常 - 改正方案 1. 处理异常 针对该异常采取一些行动, 例如修正问题 提醒某个人或进行其他一些处理, 要根据具体的情形确定应该采取的动作 再次说明, 调用 printstacktrace 算不上已经 处理好了异常 2. 重新抛出异常 处理异常的代码在分析异常之后, 认为自己不能处理它, 重新抛出异常也不失为一种选择 3. 把该异常转换成另一种异常 大多数情况下, 这是指把一个低级的异常转换成应用级的异常 ( 其含义更容易被用户了解的异常 ) 4. 不要捕获异常 结论一 : 既然捕获了异常, 就要对它进行适当的处理 不要捕获异常之后又把它丢弃, 不予理睬

1 OutputStreamWriter out =... 2 java.sql.connection conn =... 3 try { // ⑸ 4 Statement stat = conn.createstatement(); 5 ResultSet rs = stat.executequery( 6 "select uid, name from user"); 7 while (rs.next()) 8 { 9 out.println("id:" + rs.getstring("uid") // ⑹ 10 ", 姓名 :" + rs.getstring("name")); 11 } 12 conn.close(); // ⑶ (2) 不指定具体的异常! 13 out.close(); 14 } 15 catch(exception ex) // ⑵ 16 { 17 ex.printstacktrace(); //⑴,⑷ 18 } 60

Anti-pattern 61 不指定具体的异常 改正方案 找出真正的问题所在,IOException? SQLException? 结论二 : 在 catch 语句中尽可能指定具体的异常类型, 必要时使用多个 catch 不要试图处理所有可能出现的异常

1 OutputStreamWriter out =... 2 java.sql.connection conn =... 3 try { // ⑸ 4 Statement stat = conn.createstatement(); 5 ResultSet rs = stat.executequery( 6 "select uid, name from user"); 7 while (rs.next()) 8 { 9 out.println("id:" + rs.getstring("uid") // ⑹ 10 ", 姓名 :" + rs.getstring("name")); 11 } 12 conn.close(); // ⑶ 13 out.close(); 14 } 15 catch(exception ex) // ⑵ (3) 占用资源不释放! 16 { 17 ex.printstacktrace(); //⑴,⑷ 18 } 62

Anti-pattern 63 占用资源不释放 改正方案 异常改变了程序正常的执行流程 如果程序用到了文件 Socket JDBC 连接之类的资源, 即使遇到了异常, 也要正确释放占用的资源 try/catch/finally 结论三 : 保证所有资源都被正确释放 充分运用 finally 关键词

1 OutputStreamWriter out =... 2 java.sql.connection conn =... 3 try { // ⑸ 4 Statement stat = conn.createstatement(); 5 ResultSet rs = stat.executequery( 6 "select uid, name from user"); 7 while (rs.next()) 8 { 9 out.println("id:" + rs.getstring("uid") // ⑹ 10 ", 姓名 :" + rs.getstring("name")); 11 } 12 conn.close(); // ⑶ 13 out.close(); 14 } 15 catch(exception ex) // ⑵ 16 { 17 ex.printstacktrace(); //⑴,⑷ 18 } (4) 不说明异常的详细信息 64

Anti-pattern 65 不说明异常的详细信息 改正方案 printstacktrace 的堆栈跟踪功能显示出程序运行到当前类的执行流程, 但只提供了一些最基本的信息, 未能说明实际导致错误的原因, 同时也不易解读 结论四 : 在异常处理模块中提供适量的错误原因信息, 例如当前正在执行的类 方法和其他状态信息, 包括以一种更适合阅读的方式整理和组织 printstacktrace 提供的信息使其易于理解和阅读

1 OutputStreamWriter out =... 2 java.sql.connection conn =... 3 try { // ⑸ 4 Statement stat = conn.createstatement(); 5 ResultSet rs = stat.executequery( 6 "select uid, name from user"); 7 while (rs.next()) 8 { 9 out.println("id:" + rs.getstring("uid") // ⑹ 10 ", 姓名 :" + rs.getstring("name")); 11 } 12 conn.close(); // ⑶ 13 out.close(); 14 } 15 catch(exception ex) // ⑵ 16 { 17 ex.printstacktrace(); //⑴,⑷ 18 } (5) 过于庞大的 try 块 66

Anti-pattern 67 过于庞大的 try 块 改正方案 庞大的原因? 偷懒? 结论五 : 分离各个可能出现异常的段落并分别捕获其异常, 尽量减小 try 块的体积

1 OutputStreamWriter out =... 2 java.sql.connection conn =... 3 try { // ⑸ 4 Statement stat = conn.createstatement(); 5 ResultSet rs = stat.executequery( 6 "select uid, name from user"); 7 while (rs.next()) 8 { 9 out.println("id:" + rs.getstring("uid") // ⑹ 10 ", 姓名 :" + rs.getstring("name")); 11 } 12 conn.close(); // ⑶ 13 out.close(); 14 } 15 catch(exception ex) // ⑵ 16 { 17 ex.printstacktrace(); //⑴,⑷ 18 } 如果循环中出现异常, 如何? (6) 输出数据不完整 68

Anti-pattern 69 输出数据不完整 改正方案 对于有些系统来说, 数据不完整可能比系统停止运行带来更大的损失 方案 1: 向输出设备写一些信息, 声明数据的不完整性 ; 方案 2: 先缓冲要输出的数据, 准备好全部数据之后再一次性输出 结论六 : 全面考虑可能出现的异常以及这些异常对执行流程的影响

OutputStreamWriter out =... java.sql.connection conn =... try { Statement stat = conn.createstatement(); ResultSet rs = stat.executequery( "select uid, name from user"); while (rs.next()) { out.println("id:" + rs.getstring("uid") + ", 姓名 : " + rs.getstring("name")); } } catch(sqlexception sqlex) { out.println(" 警告 : 数据不完整 "); throw new ApplicationException( " 读取数据时出现 SQL 错误 ", sqlex); } catch(ioexception ioex) { throw new ApplicationException( " 写入数据时出现 IO 错误 ", ioex); } 70 finally { if (conn!= null) { try { conn.close(); } catch(sqlexception sqlex2) { System.err(this.getClass().getName() + ".mymethod - 不能关闭数据库连接 : " + sqlex2.tostring()); } } if (out!= null) { try { out.close(); } catch(ioexception ioex2) { System.err(this.getClass().getName() + ".mymethod - 不能关闭输出文件 " + ioex2.tostring()); } } }

Effective Java Exceptions 71 高效 Java 异常处理机制 : 引自 <<Effective Java TM 语法 词汇 用法 second edition>>(joshua Bloch) 高效 灵活 鲁棒 可重用的程序

9 大原则 72 Use exceptions only for exceptional conditions 只针对不正常的条件才使用异常 //Horrible abuse of exceptions. Don t ever do this! try{ int i = 0; while(true) range[i++].climb(); }catch(arrayindexoutofboundsexception e) { } 通过 ArrayIndexOutOfBoundsException 的手段来达到终止无限循环的目的 for (Mountain m : range) m.climb();

9 大原则 Use checked exceptions for recoverable conditions and runtime exceptions for programming errors 对于可恢复的条件使用被检查的异常, 对于程序错误使用运行时异常

9 大原则 Avoid unnecessary use of checked exceptions 避免不必要地使用被检查的异常

9 大原则 75 Favor the use of standard exceptions 尽量使用标准的异常 Throw exceptions appropriate to the abstraction 抛出的异常要适合于相应的抽象 Document all exceptions thrown by each method 每个方法抛出的异常都要有文档

9 大原则 76 Include failure-capture information in detail messages 在细节消息中包含失败 捕获信息 Strive for failure atomicity 努力使失败保持原子性 Don t ignore exceptions 不要忽略异常

Keep in mind 77 勿以恶小而为之, 勿以善小而不为