zoukankan      html  css  js  c++  java
  • Effective Java 59 Avoid unnecessary use of checked exceptions

    The burden is justified if the exceptional condition cannot be prevented by proper use of the API and the programmer using the API can take some useful action once confronted with the exception.

    ask yourself how the programmer will handle the exception.

       

    Is this the best that can be done?

    } catch(TheCheckedException e) {

    throw new AssertionError(); // Can't happen!

    }

    How about this?

    } catch(TheCheckedException e) {

    e.printStackTrace(); // Oh well, we lose.

    System.exit(1);

    }

       

    Principle

    1. If the programmer using the API can do no better an unchecked exception would be more appropriate. The checked nature of the exception provides no benefit to the programmer, but it requires effort and complicates programs.
    2. Turning a checked exception into an unchecked exception is to break the method that throws the exception into two methods, the first of which returns a boolean that indicates whether the exception would be thrown.
       

    // Invocation with checked exception

    try {

    obj.action(args);

    } catch(TheCheckedException e) {

    // Handle exceptional condition

    ...

    }

       

    to this:

    // Invocation with state-testing method and unchecked exception

    if (obj.actionPermitted(args)) {

    obj.action(args);

    } else {

    // Handle exceptional condition

    ...

    }

       

    If you suspect that the simple calling sequence will be the norm, then this API refactoring may be appropriate. The API resulting from this refactoring is essentially identical to the state-testing method API in Item 57 and the same caveats apply: if an object is to be accessed concurrently without external synchronization or it is subject to externally induced state transitions, this refactoring is inappropriate, as the object's state may change between the invocations of actionPermitted and action . If a separate actionPermitted method would, of necessity, duplicate the work of the action method, the refactoring may be ruled out by performance concerns.

  • 相关阅读:
    RHEL6.5安装QT5.4,设置环境变量
    Oprofile安装与使用探索
    龙芯3A上V8的编译与测试
    C#穿透session隔离———Windows服务启动UI交互程序 be
    C#获取CPU与网卡硬盘序列号及Base64和DES加密解密操作类 be
    C#读取Excel转换为DataTable be
    WPF DataGrid ScrollBar Style be
    C#操作注册表 be
    C#读取Excel转为DataTable be
    C# DataTable与Excel读取与导出 be
  • 原文地址:https://www.cnblogs.com/haokaibo/p/avoid-unnecessary-use-of-checked-exceptions.html
Copyright © 2011-2022 走看看