[转]java-Three Rules for Effective Exception Handling

时间:2022-09-24 13:36:27

主要讲java中处理异常的三个原则:

原文链接:https://today.java.net/pub/a/today/2003/12/04/exceptions.html

Exceptions in Java provide a consistent mechanism for identifying and responding to error conditions. Effective exception handling   will make your programs more robust and easier to debug. Exceptions are a tremendous debugging aid because they help answer     these three questions:

  • What went wrong?
  • Where did it go wrong?
  • Why did it go wrong?

When exceptions are used effectively, what is answered by the type of exception thrown, where is answered by the exception stack  trace, and why is answered by the exception message. If you find your exceptions aren't answering all three questions, chances are  they aren't being used effectively. Three rules will help you make the best use of exceptions when debugging your programs. These  rules are: be specific, throw early, and catch late.

To illustrate these rules of effective exception handling, this article discusses a fictional personal finance manager called JCheckbook.  JCheckbook can be used to record and track bank account activity, such as deposits, withdrawals, and checks written. The initial       version of JCheckbook runs as a desktop application, but future plans call for an HTML client and client/server applet implementation.

Be Specific

Java defines exception class hierarchy, starting with Throwable, which is extended by Error and Exception, which is then extended   by RuntimeException. These are illustrated in Figure 1.

[转]java-Three Rules for Effective Exception Handling
Figure 1. Java exception hierarchy

These four classes are generic and they don't provide much information about what went wrong. While it is legal to instantiate any   of these classes (e.g., new Throwable()), it is best to think of them as abstract base classes, and work with more specific subclasses. Java provides a substantial number of exception subclasses, and you may define your own exception classes for additional specificity.

For example, the java.io package defines the IOException subclass, which extends Exception. Even more specific are FileNotFoundException, EOFException, andObjectStreamException, all subclasses of IOException. Each one describes a particular type of I/O-related failure: a missing file, an unexpected end-of-file, or a corrupted serialized object stream, respectively. The more specific the exception, the better our program answers what went wrong.

It is important to be specific when catching exceptions, as well. For example, JCheckbook may respond to a FileNotFoundException by asking the user for a different file name. In the case of an EOFException, it may be able to continue with just the information it was able to read before the exception was thrown. If an ObjectStreamException is thrown, the program may need to inform the user that the file has been corrupted, and that a backup or a different file needs to be used.

Java makes it fairly easy to be specific when catching exceptions because we can specify multiple catch blocks for a single try block, each handling a different type of exception in an appropriate manner.

   1: File prefsFile = new File(prefsFilename);

   2:  

   3: try

   4: {    

   5:      readPreferences(prefsFile);

   6: }

   7: catch (FileNotFoundException e)

   8: {    

   9:      // alert the user that the specified file   

  10:      // does not exist

  11: }

  12: catch (EOFException e)

  13: {    

  14:      // alert the user that the end of the file    

  15:      // was reached

  16: }

  17: catch (ObjectStreamException e)

  18: {    

  19:      // alert the user that the file is corrupted

  20: }

  21: catch (IOException e)

  22: {    

  23:      // alert the user that some other I/O    

  24:      // error occurred

  25: }

JCheckbook uses multiple catch blocks in order to provide the user with specific information about the type of exception that was     caught. For instance, if a FileNotFoundException was caught, it can instruct the user to specify a different file. The extra coding effort of multiple catch blocks may be an unnecessary burden in some cases, but in this example, it does help the program respond in a more user-friendly manner.

Should an IOException other than those specified by the first three catch blocks be thrown, the last catch block will handle it by presenting the user with a somewhat more generic error message. This way, the program can provide specific information when possible, but still handle the general case should an unanticipated file-related exception "slip by."

Sometimes, developers will catch a generic Exception and then display the exception class name or stack trace, in order to "be specific." Don't do this. Seeing java.io.EOFException or a stack trace printed to the screen is likely to confuse, rather than help, the user. Catch specific exceptions and provide the user with specific information in English (or some other human language). Do, however, include the exception stack trace in your log file. Exceptions and stack traces are meant as an aid to the developer, not to the end user.

Finally, notice that instead of catching the exception in the readPreferences() method, JCheckbook defers catching and handling the exception until it reaches the user interface level, where it can alert the user with a dialog box or in some other fashion. This is what is meant by "catch late," as will be discussed later in this article.

Throw Early

The exception stack trace helps pinpoint where an exception occurred by showing us the exact sequence of method calls that lead to the exception, along with the class name, method name, source code filename, and line number for each of these method calls. Consider the stack trace below:

java.lang.NullPointerException
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(FileInputStream.java:103)
    at jcheckbook.JCheckbook.readPreferences(JCheckbook.java:225)
    at jcheckbook.JCheckbook.startup(JCheckbook.java:116)
    at jcheckbook.JCheckbook.<init>(JCheckbook.java:27)
    at jcheckbook.JCheckbook.main(JCheckbook.java:318)

This shows that the open() method of the FileInputStream class threw a NullPointerException. But notice that FileInputStream.close() is part of the standard Java class library. It is much more likely that the problem that is causing the exception to be thrown is within our own code, rather than the Java API. So the problem must have occurred in one of the preceding methods, which fortunately are also displayed in the stack trace.

What is not so fortunate is that NullPointerException is one of the least informative (and most frequently encountered and frustrating) exceptions in Java. It doesn't tell us what we really want to know: exactly what is null. Also, we have to backtrack a few steps to find out where the error originated.

By stepping backwards through the stack trace and investigating our code, we determine that the error was caused by passing a null filename parameter to the readPreferences() method. Since readPreferences() knows it cannot proceed with a null filename, it      checks for this condition immediately:

   1: public void readPreferences(String filename)

   2:     throws IllegalArgumentException

   3: {    

   4:     if (filename == null)   

   5:     {       

   6:         throw new IllegalArgumentException ("filename is null");   

   7:     }  //if

   8:     //...perform other operations...        

   9:     InputStream in = new FileInputStream(filename);        

  10:     //...read the preferences file...

  11: }

By throwing an exception early (also known as "failing fast"), the exception becomes both more specific and more accurate. The stack trace immediately shows what went wrong (an illegal argument value was supplied), why this is an error (null is not allowed for filename), and where the error occurred (early in the readPreferences() method). This keeps our stack trace honest:

java.lang.IllegalArgumentException: filename is null
    at jcheckbook.JCheckbook.readPreferences(JCheckbook.java:207)
    at jcheckbook.JCheckbook.startup(JCheckbook.java:116)
    at jcheckbook.JCheckbook.<init>(JCheckbook.java:27)
    at jcheckbook.JCheckbook.main(JCheckbook.java:318)

In addition, the inclusion of an exception message ("filename is null") makes the exception more informative by answering specifically what was null, an answer we don't get from theNullPointerException thrown by the earlier version of our code.

Failing fast by throwing exceptions as soon as an error is detected can eliminate the need to construct objects or open resources, such as files or network connections, that won't be needed. The clean-up effort associated with opening these resources is also eliminated.

Catch Late

A common mistake of many Java developers, both new and experienced, is to catch an exception before the program can handle it in an appropriate manner. The Java compiler reinforces this behavior by insisting that checked exceptions either be caught or declared. The natural tendency is to immediately wrap the code in a try block and catch the exception to stop the compile from reporting errors.

The question is, what to do with an exception after it is caught? The absolute worst thing to do is nothing. An empty catch block swallows the exception, and all information about what, where, and why something went wrong is lost forever. Logging the exception is slightly better, since there is at least a record of the exception. But we can hardly expect that the user will read or even understand the log file and stack trace. It is not appropriate for readPreferences() to display a dialog with an error message, because while JCheckbook currently runs as a desktop application, we also plan to make it an HTML-based web application. In that case, displaying an error dialog is not an option. Also, in both the HTML and the client/server versions, the preferences would be read on the server, but the error needs to be displayed in the web browser or on the client. The readPreferences() method should be designed with these future needs in mind. Proper separation of user interface code from program logic increases the reusability of our code.

Catching an exception too early, before it can properly be handled, often leads to further errors and exceptions. For example, had the readPreferences() method shown earlier immediately caught and logged the FileNotFoundException that could be thrown while calling the FileInputStream constructor, the code would look something like this:

   1: public void readPreferences(String filename) 

   2: {    

   3:     //...        

   4:     InputStream in = null;        

   5:     // DO NOT DO THIS!!!    

   6:     try    

   7:     {        

   8:         in = new FileInputStream(filename);    

   9:     }    

  10:     catch (FileNotFoundException e)    

  11:     {        

  12:         logger.log(e);    

  13:     }        

  14:     in.read(...);       

  15:      //...

  16: }

This code catches FileNotFoundException, when it really cannot do anything to recover from the error. If the file is not found, the rest of the method certainly cannot read from the file. What would happen should readPreferences() be called with the name of file that doesn't exist? Sure, the FileNotFoundException would be logged, and if we happened to be looking at the log file at the time, we'd be aware of this. But what happens when the program tries to read data from the file? Since the file doesn't exist, in is null, and a NullPointerException gets thrown.

When debugging a program, instinct tells us to look at the latest information in the log. That's going to be the NullPointerException, dreaded because it is so unspecific. The stack trace lies, not only about what went wrong (the real error is a FileNotFoundException, not a NullPointerException), but also about where the error originated. The problem occurred several lines of code away from where the NullPointerException was thrown, and it could have easily been several method calls and classes removed. We end up wasting time chasing red herrings that distract our attention from the true source of the error. It is not until we scroll back in the log file that we see what actually caused the program to malfunction.

What should readPreferences() do instead of catching the exceptions? It may seem counterintuitive, but often the best approach is to simply let it go; don't catch the exception immediately. Leave that responsibility up to the code that calls readPreferences(). Let that code determine the appropriate way to handle a missing preferences file, which could mean prompting the user for another file, using default values, or, if no other approach works, alerting the user of the problem and exiting the application.

The way to pass responsibility for handling exceptions further up the call chain is to declare the exception in the throws clause of the method. When declaring which exceptions may be thrown, remember to be as specific as possible. This serves to document what types of exceptions a program calling your method should anticipate and be ready to handle. For example, the "catch late" version of the readPreferences() method would look like this:

   1: public void readPreferences(String filename)    

   2:     throws IllegalArgumentException,

   3:            FileNotFoundException, IOException

   4: {    

   5:     if (filename == null)    

   6:     {        

   7:         throw new IllegalArgumentException ("filename is null");    

   8:     }  //if       

   9:     //...       

  10:     InputStream in = new FileInputStream(filename);

  11:     //...

  12: }

Technically, the only exception we need to declare is IOException, but we document our code by declaring that the method may specifically throw a FileNotFoundException.IllegalArgumentException need not be declared, because it is an unchecked exception (a subclass of RuntimeException). Still, including it serves to document our code (the exceptions should also be noted in the JavaDocs for the method).

Of course, eventually, your program needs to catch exceptions, or it may terminate unexpectedly. But the trick is to catch exceptions at the proper layer, where your program can either meaningfully recover from the exception and continue without causing further errors, or provide the user with specific information, including instructions on how to recover from the error. When it is not practical for a method to do either of these, simply let the exception go so it can be caught later on and handled at the appropriate level.

Conclusion

Experienced developers know that the hardest part of debugging usually is not fixing the bug, but finding where in the volumes of code the bug hides. By following the three rules in this article, you can help exceptions help you track down and eradicate bugs and make your programs more robust and user-friendly.

[转]java-Three Rules for Effective Exception Handling的更多相关文章

  1. Exception &lpar;2&rpar; Java Exception Handling

    The Java programming language uses exceptions to handle errors and other exceptional events.An excep ...

  2. Java – Top 5 Exception Handling Coding Practices to Avoid

    This article represents top 5 coding practices related with Java exception handling that you may wan ...

  3. Exception &lpar;3&rpar; Java exception handling best practices

    List Never swallow the exception in catch block Declare the specific checked exceptions that your me ...

  4. Java exception handling best practices--转载

    原文地址:http://howtodoinjava.com/2013/04/04/java-exception-handling-best-practices/ This post is anothe ...

  5. Java异常:选择Checked Exception还是Unchecked Exception&quest;

    http://blog.csdn.net/kingzone_2008/article/details/8535287 Java包含两种异常:checked异常和unchecked异常.C#只有unch ...

  6. Exception Handling in ASP&period;NET Web API

    public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErr ...

  7. 异常处理与MiniDump详解&lpar;3&rpar; SEH(Structured Exception Handling)

    write by 九天雁翎(JTianLing) -- blog.csdn.net/vagrxie 讨论新闻组及文件 一.   综述 SEH--Structured Exception Handlin ...

  8. Exception handling 异常处理的本质

    异常处理的本质:状态回滚或者状态维护. https://en.wikipedia.org/wiki/Exception_handling In general, an exception breaks ...

  9. &lbrack;fw&rsqb;Best Practices for Exception Handling

    http://www.onjava.com/pub/a/onjava/2003/11/19/exceptions.html http://www.onjava.com/pub/a/onjava/200 ...

随机推荐

  1. token验证 sae

    在微信平台中修改服务器设置时,使用微信Demo的php,刚开始一直验证token 失败 解决办法 :在echo $echoStr;之前添加header('content-type:text');一句这 ...

  2. C&num;压缩字符串

    在论坛上看到一个压缩字符串的问题,特此记录以备后用! static string GetStringR(string inputStr) { return Regex.Replace(inputStr ...

  3. percona-xtrabackup安装

    二进制包安装(推荐安装方式,不用安装依赖包,非常方便): 1.下载安二进制包:      wget https://www.percona.com/downloads/XtraBackup/Perco ...

  4. mac搭建简单的hls推流服务器遇到的问题&lpar;待更新&rpar;

    实际操作步骤: 输入brew install nginx-full --with-rtmp-module命令出现以下报错: 需要先安装nginx服务器,运行命令brew tap homebrew/ng ...

  5. nyoj 单调递增子序列&lpar;二&rpar;

    单调递增子序列(二) 时间限制:1000 ms  |  内存限制:65535 KB 难度:4   描述 给定一整型数列{a1,a2...,an}(0<n<=100000),找出单调递增最长 ...

  6. Java WebService Axis 初探

    最近在学习WebService 开始了: 一:服务端的编写与发布 1. 工具准备: java的开发环境(这里就不多说了).   axis2官网上下载最新的就可以了(我这里用的是axis2-1.4.1- ...

  7. Centos更新配置文件命令

    source 命令是 bash shell 的内置命令,从 C Shell 而来.source 命令的另一种写法是点符号,用法和 source 相同,从Bourne Shell而来.source 命令 ...

  8. flutter 交互提示方式

    交互提示方式dialog和snackbar 首先看看dialog的方式 new PopupMenuButton( icon: new Icon(Icons.phone_iphone, color: C ...

  9. DriverStore文件夹特别大,能删除吗?

    DriverStore文件夹特别大,能删除吗? DriverStore\FileRepository文件夹特别大,能删除吗? C:\Windows\System32\DriverStore\FileR ...

  10. C语言学习笔记--条件编译

    C语言中的条件编译的行为类似于 C 语言中的 if…else…,是预编译指示命令,用于控制是否编译某段代码 . 1.条件编译的本质 (1)预编译器根据条件编译指令有选择的删除代码 (2)编译器不知道代 ...