TIJ——Chapter Twelve:Error Handling with Exception
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) An error you cannot anticipate. For example, a null reference that is outside of your control.
- (#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的更多相关文章
- Error Handling and Exception
The default error handling in PHP is very simple.An error message with filename, line number and a m ...
- Clean Code–Chapter 7 Error Handling
Error handling is important, but if it obscures logic, it's wrong. Use Exceptions Rather Than Return ...
- 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 ...
- Error Handling
Use Exceptions Rather Than Return Codes Back in the distant past there were many languages that didn ...
- beam 的异常处理 Error Handling Elements in Apache Beam Pipelines
Error Handling Elements in Apache Beam Pipelines Vallery LanceyFollow Mar 15 I have noticed a defici ...
- Fortify漏洞之Portability Flaw: File Separator 和 Poor Error Handling: Return Inside Finally
继续对Fortify的漏洞进行总结,本篇主要针对 Portability Flaw: File Separator 和 Poor Error Handling: Return Inside Fina ...
- 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 ...
- WCF Error Handling
https://docs.microsoft.com/en-us/dotnet/framework/wcf/wcf-error-handling The errors encountered by a ...
- ASP.NET Error Handling
https://docs.microsoft.com/en-us/aspnet/web-forms/overview/getting-started/getting-started-with-aspn ...
随机推荐
- Jupyter notebook使用matplotlib不出图解决办法
1.在jupyter notebook使用plot的时候没有显示图像2.在命令行知道需要使用ipython --pylab进入ipython环境才能做出图像,jupyter notebook该怎么设置 ...
- Leetcode429.N-ary Tree Level Order TraversalN叉树的层序遍历
给定一个 N 叉树,返回其节点值的层序遍历. (即从左到右,逐层遍历). 例如,给定一个 3叉树 : 返回其层序遍历: [ [1], [3,2,4], [5,6] ] 说明: 树的深度不会超过 100 ...
- TZ_13_Eureka的高可用
1.Eureka Server即服务的注册中心,在刚才上一篇中,我们只有一个EurekaServer,事实上EurekaServer也可以是一个集群,形成高可用的Eureka中心. 目的:多个Eure ...
- 修改input标签输入样式
去掉input自带的边框: border-style:none;修改input输入的文字样式: input{ font-size: 24px; color:#5d6494; } 修改input框中占位 ...
- Hackerrank--Emma and sum of products (FFT)
题目链接 Emma is really fond of integers and loves playing with them. Her friends were jealous, and to t ...
- ubuntu 12.4,搞定apt源
http://wiki.ubuntu.org.cn/Template:12.04source deb http://cn.archive.ubuntu.com/ubuntu/ precise main ...
- docker-4-Dockerfile配置文件详解
Dockerfile简单一点就是描述你这个镜像安装了哪些软件包,有哪些操作,创建了什么东西.有些人喜欢用 docker commit 命令去打包镜像,这样是不好的,首先commit出来的镜像比你使 ...
- Apache-Shiro分布式环境配置(与redis集成)(转)
原文戳我 前段时间项目要用到权限控制的相关模块,经过讨论决定采用Apache下面的Shiro开源框架进行身份校验与权限控制,因项目需部署在集群环境下,所以需要分布式的支持,故配置了Redis作为权限数 ...
- Leetcode501.Find Mode in Binary Search Tree二叉搜索树中的众数
给定一个有相同值的二叉搜索树(BST),找出 BST 中的所有众数(出现频率最高的元素). 假定 BST 有如下定义: 结点左子树中所含结点的值小于等于当前结点的值 结点右子树中所含结点的值大于等于当 ...
- Leetcode669.Trim a Binary Search Tree修建二叉树
给定一个二叉搜索树,同时给定最小边界L 和最大边界 R.通过修剪二叉搜索树,使得所有节点的值在[L, R]中 (R>=L) .你可能需要改变树的根节点,所以结果应当返回修剪好的二叉搜索树的新的根 ...