加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java异常处理的最佳实践

发布时间:2020-12-14 23:35:51 所属栏目:Java 来源:网络整理
导读:我最近写了下面的代码;它使用了很多异常处理.我认为它使代码看起来非常难以理解.我可以通过捕获泛型异常来缩短代码,例如 catch (Exception e){ e.printStackTrace();} 但我也听说过捕获一般异常不是一个好的编码实践. public class DataAnalyzerTester { /**
我最近写了下面的代码;它使用了很多异常处理.我认为它使代码看起来非常难以理解.我可以通过捕获泛型异常来缩短代码,例如
catch (Exception e){
    e.printStackTrace();
}

但我也听说过捕获一般异常不是一个好的编码实践.

public class DataAnalyzerTester {
    /**
     * @param args args[0] stores the filename
     * @exception NoSuchElementException if user attempts to access empty list element
     * @exception ArithmeticException if user attempts to divide by 0
     * @exception ArrayIndexOutOfBoundsException if user supplied less than 3 arguments
     * @exception IOException problems with creating and writing files
     * @exception RuntimeException if user attempts to pass empty list to constructor
     */
    public static void main(String[] args) {

    try{
        //some code

    } catch (NoSuchElementException e) {
        System.out.println("Accessing element that does not exist: " + e.toString());
    } catch (ArithmeticException e) {
        System.out.println("Division by zero: " + e.toString());
    } catch (ArrayIndexOutOfBoundsException e) {
        System.out.println("Please supply a command line arguement that specifies your file path: " + e.toString());
    } catch (IOException e) {
        System.out.println("Other IO errors: " + e.toString());
    } catch (RuntimeException e) {
        System.out.println(e.toString());
    } 
    }
}

我想知道是否有更好,更清晰的方法来捕获多个异常.

解决方法

首先,除非你有充分的理由,否则永远不会捕获RuntimeException,Exception或Throwable.这些将捕获大多数抛出的东西,Throwable将捕获所有内容,甚至是那些你不想捕获的东西,比如OutOfMemoryError.

其次,避免捕获运行时异常,除非它直接阻碍程序的关键操作. (但严重的是,如果有人看到你发现了NullPointerException,那么他们完全有权在你身上打电话给你.)你唯一需要注意的例外是那些你需要处理的例外.在您的异常列表中,您唯一应该打扰的是IOException.其余的是没有足够的测试或草率编码的结果;那些不应该在您的应用程序的正常运行时间内发生.

第三,在Java 7中,如果异常是互斥的,您可以为异常执行multi-catch语句.链接的示例很好地解释了它,但如果您遇到同时抛出IOException和SQLException的代码,您可以像这样处理它:

try {
    // Dodgy database code here
catch (IOException|SQLException ex) {
    logger.log(ex);
    throw ex;
}

这会清理一些事情,因为你没有笨拙和庞大的异常链.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读