Error Handling with Exceptions


  • The ideal time to catch an error is at compile time, before you even try to run the program.
  • The rest of the problems must be handled at run time through some formality that allows the originator of the error to pass appropriate information to a recipient who will know how to handle the difficulty properly.
  • To create a robust system, each component must be robust.
  • By providing a consistent error-reporting model using exceptions, Java allows components to reliably communicate problems to client code.

Concepts

  • At the point where the problem occurs, you might not know what to do with it, but you do know that you can’t just continue on merrily.
  • You don’t have enough information in the current context to fix the problem. So you hand the problem out to a higher context where someone is qualified to make the proper decision.
  • You only need to handle the problem in one place, in the so-called exception handler.

Basic exceptions

  • With an exceptional condition, you cannot continue processing because you don’t have the information necessary to deal with the problem in the current context.
  • All you can do is jump out of the current context and relegate that problem to a higher context. This is what happens when you throw an exception.
  • You can send information about the error into a larger context by creating an object representing your information and "throwing" it out of your current context. This is called throwing an exception.
  • Exceptions allow you to think of everything that you do as a transaction, and the exceptions guard those transactions.
  • Exceptions allow you to (if nothing else) force the program to stop and tell you what went wrong, or (ideally) force the program to deal with the problem and return to a stable state.

Exception arguments

  • There are two constructors in all standard exceptions: The first is the default constructor, and the second takes a string argument so that you can place pertinent information in the exception.
  • After creating an exception object with new, you give the resulting reference to throw.
  • A simplistic way to think about exception handling is as a different kind of return mechanism.
  • You can throw any type of Throwable, which is the exception root class.

Catching an exception

  • guarded region is a section of code that might produce exceptions and is followed by the code to handle those exceptions.

The try block

  • If you don’t want a throw to exit the method, you can set up a special block within that method to capture the exception.
  • With exception handling, you put everything in a try block and capture all the exceptions in one place.

Exception handlers

  • The thrown exception must end up someplace. This "place" is the exception handler.
  • Sometimes you never use the identifier because the type of the exception gives you enough information to deal with the exception.
  • If an exception is thrown, the exception-handling mechanism goes hunting for the first handler with an argument that matches the type of the exception.

Termination vs. resumption

  • termination: you assume that the error is so critical that there’s no way to get back to where the exception occurred.
  • resumption: the exception handler is expected to do something to rectify the situation, and then the faulting method is retried, presuming success the second time.
  • If you want resumption-like behavior in Java, don’t throw an exception when you encounter an error.
  • Although resumption sounds attractive at first, it isn’t quite so useful in practice.

Creating your own exceptions

  • The most trivial way to create a new type of exception is just to let the compiler create the default constructor for you.
  • The most important thing about an exception is the class name.
  • If you send output to System.err, it will not be redirected along with System.out so the user is more likely to notice it.

Exceptions and logging

  • It’s more common that you will be catching and logging someone else’s exception, so you must generate the log message in the exception handler.
  • All this dressing-up might be lost on the client programmers using your packages, since they might simply look for the exception to be thrown and nothing more.

The exception specification

  • exception specification: Java provides syntax (and forces you to use that syntax) to allow you to politely tell the client programmer what exceptions this method throws.
  • You must either handle the exception or indicate with an exception specification that it may be thrown from your method.
  • You can actually start throwing the exception later without requiring changes to existing code.
  • Exceptions that are checked and enforced at compile time are called checked exceptions.

Catching any exception

  • Since the Exception class is the base of all the exception classes that are important to the programmer, you don’t get much specific information about the exception, but you can call the methods that come from its base type Throwable.

The stack trace

  • getStackTrace( ) method returns an array of stack trace elements, each representing one stack frame.

Rethrowing an exception

  • Rethrowing an exception causes it to go to the exception handlers in the nexthigher context.
  • Everything about the exception object is preserved, so the handler at the higher context that catches the specific exception type can extract all the information from that object.
  • It’s also possible to rethrow a different exception from the one you caught.
  • You never have to worry about cleaning up the previous exception, or any exceptions for that matter.

Exception chaining

  • exception chainin: you want to catch one exception and throw another, but still keep the information about the originating exception.
  • The cause is intended to be the originating exception, and by passing it in you maintain the stack trace back to its origin.

Standard Java exceptions

  • There are two general types of Throwable objects.
  • Error represents compile-time and system errors that you don’t worry about catching.
  • 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.

Special case: RuntimeException

  • If any call is made to a null reference, Java will automatically throw a NullPointerException.
  • You never need to write an exception specification saying that a method might throw a RuntimeException, because they are unchecked exceptions.
  • A RuntimeException(or anything inherited from it) is a special case, since the compiler doesn’t require an exception specification for these types.
  • A RuntimeException represents a programming error.

Performing cleanup with finally

  • There’s often some piece of code that you want to execute whether or not an exception is thrown within a try block.
  • Exceptions in Java do not allow you to resume back to where the exception was thrown.

What’s finally for?

  • finally is important because it allows the programmer to guarantee the release of memory regardless of what happens in the try block.
  • The finally clause is necessary when you need to set something other than memory back to its original state.
  • Along with the labeled break and labeled continue, finally eliminates the need for a goto statement in Java.

Using finally during return

  • Because a finally clause is always executed, it’s possible to return from multiple points within a method and still guarantee that important cleanup will be performed.

Pitfall: the lost exception

  • It’s possible for an exception to simply be lost. This happens with a particular configuration using a finally clause.
  • Using ‘return’ inside the finally block will silence any thrown exception.

Exception restrictions

  • When you override a method, you can throw only the exceptions that have been specified in the base-class version of the method.
  • Interface CANNOT add exceptions to existing methods from the base class, this makes sense because otherwise you’d never know if you were catching the correct thing when working with the base class.
  • The restriction on exceptions does not apply to constructors.
  • The derived-class constructor must declare any base-class constructor exceptions in its exception specification.
  • By forcing the derived-class methods to conform to the exception specifications of the base-class methods, substitutability of objects is maintained.
  • A derived-class version of a method may choose not to throw any exceptions, even if the base-class version does.
  • The exception specifications are not part of the type of a method, which comprises only the method name and argument types.
  • The "exception specification interface" for a particular method may narrow during inheritance and overriding, but it may not widen.

Constructors

  • If you throw an exception from inside a constructor, these cleanup behaviors might not occur properly.
  • If a constructor fails partway through its execution, it might not have successfully created some part of the object that will be cleaned up in the finally clause.
  • One of the design issues with exceptions is whether to handle an exception completely at this level, to handle it partially and pass the same exception (or a different one) on, or whether to simply pass it on.
  • The basic rule is: Right after you create an object that requires cleanup, begin a try-finally.

Exception matching

  • When it finds a match, the exception is considered handled, and no further searching occurs.
  • Matching an exception doesn’t require a perfect match between the exception and its handler.
  • If you decide to add more derived exceptions to a method, then the client programmer’s code will not need changing as long as the client catches the base-class exceptions.

Alternative approaches

  • It’s worth observing that the issue of programmer convenience in handling errors was a prime motivation for exceptions in the first place.
  • One of the important goals of exception handling is to move the error-handling code away from the point where the errors occur.
  • Exception handling also tends to reduce the amount of error-handling code, by allowing one handler to deal with many error sites.
  • Because the compiler forces you to write code right away to handle the exception, this seems like the easiest solution even though it’s probably the worst thing you can do.

History

  • To draw them into a better way of handling errors, the amount of code they would need to "add" must not be onerous.
  • The exception specification really has two purposes.
  • In C++, no compile-time checking occurs to determine whether or not the function or method will actually throw that exception, or whether the exception specification is complete.
  • In Java, there are restrictions on the way that Java generics can be used with exception specifications.

Perspectives

  • Java’s important step was to unify the error-reporting model, so that all errors are reported using exceptions.
  • When Java modified the C++ model so that exceptions were the only way to report errors, the extra enforcement of checked exceptions may have become less necessary.
  • It’s even more important to realize the limitation of what the compiler is able to do.
  • In any event, the likelihood of checked exceptions ever being removed from Java seems dim.
  • However, if you find that some checked exceptions are getting in your way, or especially if you find yourself being forced to catch exceptions, but you don’t know what to do with them, there are some alternatives.

Passing exceptions to the console

  • Note that main( ) is also a method that may have an exception specification.
  • By passing it out to the console, you are relieved from writing try-catch clauses within the body of main( ).

Converting checked to unchecked exceptions

  • You simply "wrap" a checked exception inside a RuntimeException by passing it to the RuntimeException constructor.

Thinking in Java——笔记(12)的更多相关文章

  1. Java笔记12:Java对象排序

    代码: import java.util.Arrays; import java.util.Comparator; class Person { private String name; privat ...

  2. java笔记12之面向对象初始

    1 概述 类:是一组相关的属性和行为的集合.是一个抽象的概念.     对象:是该类事物的具体表现形式.具体存在的个体. (1)面向对象思想     面向对象是基于面向过程的编程思想.         ...

  3. JAVA自学笔记12

    JAVA自学笔记12 1.Scanner 1)JDK5后用于获取用户的键盘输入 2)构造方法:public Scanner(InputStream source) 3)System.in 标准的输入流 ...

  4. Spring MVC 学习笔记12 —— SpringMVC+Hibernate开发(1)依赖包搭建

    Spring MVC 学习笔记12 -- SpringMVC+Hibernate开发(1)依赖包搭建 用Hibernate帮助建立SpringMVC与数据库之间的联系,通过配置DAO层,Service ...

  5. java笔记整理

    Java 笔记整理 包含内容     Unix Java 基础, 数据库(Oracle jdbc Hibernate pl/sql), web, JSP, Struts, Ajax Spring, E ...

  6. 并发编程学习笔记(12)----Fork/Join框架

    1. Fork/Join 的概念 Fork指的是将系统进程分成多个执行分支(线程),Join即是等待,当fork()方法创建了多个线程之后,需要等待这些分支执行完毕之后,才能得到最终的结果,因此joi ...

  7. SpringMVC:学习笔记(12)——ThreadLocal实现会话共享

    SpringMVC:学习笔记(12)——ThreadLocal实现会话共享 ThreadLocal ThreadLocal,被称为线程局部变量.在并发编程的情况下,使用ThreadLocal创建的变量 ...

  8. Effective Java笔记一 创建和销毁对象

    Effective Java笔记一 创建和销毁对象 第1条 考虑用静态工厂方法代替构造器 第2条 遇到多个构造器参数时要考虑用构建器 第3条 用私有构造器或者枚举类型强化Singleton属性 第4条 ...

  9. 机器学习实战 - 读书笔记(12) - 使用FP-growth算法来高效发现频繁项集

    前言 最近在看Peter Harrington写的"机器学习实战",这是我的学习心得,这次是第12章 - 使用FP-growth算法来高效发现频繁项集. 基本概念 FP-growt ...

随机推荐

  1. js 时间构造函数

    js 时间构造函数,js中没有类似ToString("yyyy-mm-dd HH:mm:ss") 的方法,但是可以用下面的方式来初始化 var cdate = new Date(& ...

  2. java13

    1:登录注册案例(理解) 2:Set集合(理解) (1)Set集合的特点 无序,唯一 (2)HashSet集合(掌握) A:底层数据结构是哈希表(是一个元素为链表的数组) B:哈希表底层依赖两个方法: ...

  3. linux svn 搭建

    原文:http://jingyan.baidu.com/article/3c343ff7039de20d37796306.html和http://blog.sina.com.cn/s/blog_670 ...

  4. 【转】Caffe初试(四)数据层及参数

    要运行caffe,需要先创建一个模型(model),如比较常用的Lenet,Alex等,而一个模型由多个层(layer)构成,每一层又由许多参数组成.所有的参数都定义在caffe.proto这个文件中 ...

  5. 使用JDK开发WebService

    一.WebService的开发手段 使用Java开发WebService时可以使用以下两种开发手段 1. 使用JDK开发(1.6及以上版本) 2.使用CXF框架开发(工作中) 二.使用JDK开发Web ...

  6. Ubuntu菜鸟入门(二)—— apt认知,且完善语言安装包

    一  语言安装包安装 1  原因 虽然安装的中文版,但是由于安装包很小,所以汉化的不够完全,所以要安装后,再下载语言包进行安装 2  方法 二  apt--软件包管理器 1   软件源 (1) 介绍 ...

  7. [工作中的设计模式]享元模式模式FlyWeight

    一.模式解析 Flyweight在拳击比赛中指最轻量级,即“蝇量级”或“雨量级”,这里选择使用“享元模式”的意译,是因为这样更能反映模式的用意.享元模式是对象的结构模式.享元模式以共享的方式高效地支持 ...

  8. Only Link: What's the difference between dynamic dispatch and dynamic binding

    http://stackoverflow.com/questions/20187587/what-is-the-difference-between-dynamic-dispatch-and-late ...

  9. BZOJ2471 : Count

    考虑KMP,设$f[i][j][S]$表示还剩最低$i$位没有确定,目前KMP匹配到了$j$这个位置,前缀匹配情况是$S$,最终会匹配到哪里,中途匹配成功几次. 其中$S[i]$是一个pair< ...

  10. PHP-Redis扩展使用手册(三)

    /* 序列化key对应的value,如果key不存在则返回false * @param key * @return 序列化后的val或者false */ $redis->set('key_1', ...