Exception guidelines

Use exceptions to:

  • Handle problems at the appropriate level.(Avoid catching exceptions unless you know what to do with them.)
  • Fix the problem and call the method that caused the exception again.
  • Patch things up and continue without retrying the method.
  • Calculate some alternative result instead of what the method was supposed to produce.
  • Do whatever you can in the current context and rethrow the same exception to a higher context.
  • Do whatever you can in the current context and throw a different exception to a higher context.
  • Terminate the program.
  • Simplify.(If your exception scheme make things more complicated, then it is painful and annoying to use.)
  • Make your library and program safer.(This is a short-term investment of debugging, and a long-term investment for application robustness.)

  • If you're inside a method and you throw an exception(or another method that you call within this method throws an exception), that method will exit in the process of throwing. If you don't  want a throws to exit the method, you can set up a special block within that method to capture the exception. This is called the try block because you "try" your various method calls there.
  • Exercise: Create your own resumption-like behavior using a while loop that repeats until an exception is no longer thrown.
class ResumerException extends Exception {}

class Resumer
{
static int count = 3;
static void f() throws ResumerException
{
if(--count > 0)
throw new ResumerException();
}
} public class Test
{
public static void main(String[] args)
{
while(true)
{
try
{
Resumer.f();
}
catch(ResumerException e)
{
System.out.println("Caught " + e);
continue;
}
System.out.println("Got through...");
break;
}
System.out.println("Successful execution");
}
}
/* Output:
Caught com.tij.ibook.ResumerException
Caught com.tij.ibook.ResumerException
Got through...
Successful execution
*/

  由上面的代码,可以给我们启示:我们甚至可以指定出现异常的代码最多执行的次数。比如,有一个可能会由于我们的网络不稳定等原因导致的网络连接超时异常,这时我们可以尝试再次连接。通过这种方式,我们可以构建更加健壮的程序。

  • The Java class Throwable describes anything that can be thrown as an exception. There are two general type of Throwable objects("types of"="inherited from"). Error represents compile-time and system errors that you don't worry about catching(except in very special cases). Exception is the basic type that can be thrown from any of the standard Java library class methods and from your methods and runtime accidents. So the Java programmer's base type of interest is usually Exception.
  • There's whole group of exception types that are in this category. They're always thrown automatically by Java and you don't need to include them in your exception specifications, Conveniently enough, they're all grouped together by putting them under a single base class called RuntimeException, which is a perfect example of inheritance: It establishes a family of types that have some characteristics and behaviors in common. Also, you never need to write an exception specification saying that a method might throw a RuntimeException(or any type inherited from RuntimeException), because they are unchecked exceptions.
  • If a RuntimeException gets all the way out to main() without being caught, printStackTrace() is called for that exception as the program exits.
  • Keep in mind that only exceptions of type RuntimeException(and subclass) can be ignored in your coding, since the compiler carefully enforces the handling of all checked exceptions. The reasoning is that a RuntimeException represents a programming error, which is:
    1. (#1)  An error you cannot anticipate. For example, a null reference that is outside of your control.
    2. (#2)  An error that tyou, as a programmer, should have checked for in your code(such as ArrayIndexOutOfBoundsException where you should have paid attention to the size of array). An exception that happens from point #1 often becomes an issue for point #2.
  • You can see what a tremendous benifit it is to have exception in Java, since they help in the debugging process.
  • In a language without garbage collection and without automatic destructor calls, finally is important because it allows the programmer to guarantee the release of memory regardless of what happens in the try block. But Java has garbage collection, so releasing memory is virtually never a problem. Also, it has no destructors to call. So when do you need to use finally in Java? The finally clause is necessary when you need to set something other than memory back to its original state. Such as some kind of cleanup like an open file or network connection, something you've drawn on the screen, or even a swith in the outside world.
  • The finally statement will also be executed in situations in which break, continue and return statements are involved.
  • When you override a method, you can throw only the exceptions that hava been specified in the base-class will automatically work with any object derived from the base class(a fundamental OOP concept, of course), including exceptions. By forcing the derived-class methods to conform to the exception specifications of the base-class methods, substitutability of objects is maintained. The restiction on exception does not apply to constructors. A constructor can throw anything it wants, regardless of what the base-class constructor throws. However, since a base-class constructor must always be called one way or another, the derived-class constructor must declare any base-class constructor exceptions in its exception specification. All these constraints produce much more robust exceptionhandling code.
  • 通过多个catch 块来捕获异常时,需要把父类型的catch 块放到子类型的catch 块之后,否则编译器会因子类型的catch 无法到达而报错。
  • The exception specification, to programmatically state in the method signature the exceptions that could result from calling that method. The exception specification really has two purposes. It can say, "I'm originating this exception in my code; you handle it." But it can also mean, "I'm ignoring this exception that can occur as a result of my code; you handle it." We've been focusing on the "you handle it" part when looking at the machanics and syntax of exceptions, but here I'm particularly interested in the fact that we often ignore exception and that's what the exception specification can state.

A good programming language is one that helps programmers write good programs. No programming language will prevent its users from writing bad programs.

TIJ——Chapter Twelve:Error Handling with Exception的更多相关文章

  1. Error Handling and Exception

    The default error handling in PHP is very simple.An error message with filename, line number and a m ...

  2. Clean Code–Chapter 7 Error Handling

    Error handling is important, but if it obscures logic, it's wrong. Use Exceptions Rather Than Return ...

  3. setjmp()、longjmp() Linux Exception Handling/Error Handling、no-local goto

    目录 . 应用场景 . Use Case Code Analysis . 和setjmp.longjmp有关的glibc and eglibc 2.5, 2.7, 2.13 - Buffer Over ...

  4. Error Handling

    Use Exceptions Rather Than Return Codes Back in the distant past there were many languages that didn ...

  5. beam 的异常处理 Error Handling Elements in Apache Beam Pipelines

    Error Handling Elements in Apache Beam Pipelines Vallery LanceyFollow Mar 15 I have noticed a defici ...

  6. Fortify漏洞之Portability Flaw: File Separator 和 Poor Error Handling: Return Inside Finally

    继续对Fortify的漏洞进行总结,本篇主要针对 Portability Flaw: File Separator 和  Poor Error Handling: Return Inside Fina ...

  7. Error handling in Swift does not involve stack unwinding. What does it mean?

    Stack unwinding is just the process of navigating up the stack looking for the handler. Wikipedia su ...

  8. WCF Error Handling

    https://docs.microsoft.com/en-us/dotnet/framework/wcf/wcf-error-handling The errors encountered by a ...

  9. ASP.NET Error Handling

    https://docs.microsoft.com/en-us/aspnet/web-forms/overview/getting-started/getting-started-with-aspn ...

随机推荐

  1. HBase性能优化方法总结 (转)

    AutoFlush 通过调用HTable.setAutoFlushTo(false)方法可以将HTable写客户端自动flush关闭,这样可以批量写入数据到HBase,而不是有一条put就执行一次更新 ...

  2. javascript基础:事件

    事件: 概念:某些组件被执行了某些操作后,触发某些代码的执行 *  事件:某些操作,如:单击,双击,键盘按下了,鼠标移动了 *  事件源:组件.如:按钮   文本输入框.... *  监听器:代码 * ...

  3. Leetcode82. Remove Duplicates from Sorted List II删除排序链表中的重复元素2

    给定一个排序链表,删除所有含有重复数字的节点,只保留原始链表中 没有重复出现 的数字. 示例 1: 输入: 1->2->3->3->4->4->5 输出: 1-&g ...

  4. promise的实现方式和运行机制

    promise的规范其实种类很多,我们最常用的是promise/A+ 这篇文章会先将一个类似于promise的构造函数怎么写,网上很多教程并没有实现A+规范,只是看起来像而已 然后我们深入探究如何一步 ...

  5. Hdu 1403(后缀数组)

    题目链接 Longest Common Substring Time Limit: 8000/4000 MS (Java/Others)    Memory Limit: 65536/32768 K ...

  6. 直接在安装了redis的Linux机器上操作redis数据存储类型--String类型

    一.概述: 字符串类型是Redis中最为基础的数据存储类型,它在Redis中是二进制安全的,这便意味着该类型可以接受任何格式的数据,如JPEG图像数据或Json对象描述信息等.在Redis中字符串类型 ...

  7. 分布式事务 XA 两段式事务 X/open CAP BASE 一次分清

    分布式事务: 分布式事务是处理多节点上 的数据保持 类似传统 ACID 事物特性的 一种事物. XA:是一种协议,一种分布式事务的协议,核心思想是2段式提交. 1 准备阶段  2 提交阶段.XA协议是 ...

  8. Mac下载Navicat premium提示文件损坏的解决方案

    首先打开终端,执行: sudo bash 这时会提示你输入你的账户密码, 输入完后就切换到了 root 用户,然后执行: xattr -cr /Applications/Navicat\ Premiu ...

  9. MYSQL基础常识

    所有的数据库名.表名.表字段都是区分大小写的.所以在使用mysql命令时需要输入正确的名称 MYSQL命令终止符是分号; 1.MYSQL的连接:mysql -u root -p(\q或exit退出); ...

  10. 考试总结 模拟28(W)

    心得: 状态极差,都怪放假,上一套的T3没改完,今天考试没有一点状态,开学恐惧症.(不恐惧作业或一调但还是很茫然) T1能A掉实在是意外,杂题T1没做过,可能是人品守恒,(丢了钱今天才发现以后一定锁柜 ...