异常处理的设计(二)

来源:互联网 发布:游戏编程工资 编辑:程序博客网 时间:2024/06/06 09:36
接着昨天的来。没有记错的话,我昨天说过在新版本中同样一个api抛出一个新的异常会导致不兼容。我今天勇于承认,这句话不太严谨,毕竟异常也是类,类支持继承,完全可以定义子类型来确保这种兼容。It's show time!. 假设我们在第一个版本中有这样一段代码:

      public static int compute(int x) throws IOException {
     if (x <= 0) throw new IOException("I just cannot deal with this!");
     return x;
    }
   

显然虽然代码看起很弱智,但是还是可以举个被调用的例子:

               int result;
     try {
       result = compute(-1);
     } catch (IOException ex) {
       Logger.getLogger("mylogger").log(Level.WARNING, "Problem!", ex);
       result = 0;
     }

作为代码的作者,某天他睡了一个好觉,他恍然大悟,他说好 我们让它不那么弱智,他准备先改改异常,他要让以前的用户继续可用(兼容),还要写个更好的异常,能给出一个更有信息量的异常,于是他这么写:

 public static int compute(int x) throws IOException {      if (x<= 1) throw new EnhancedIOException(x);      return x;    }         public final class EnhancedIOException extends IOException {      int x;      EnhancedIOException(int x) {        super("I just cannot deal with this!");        this.x = x;      }           public int getX() { return x; }    }
因为 EnhancedIOException extends IOException  以前的catch同样奏效,并且现在我们有多了一个选择:

                        int result;
    try {
     result = compute(-1);
    } catch (EnhancedIOException ex) {
     // compute ourselves meaningful result:
     result = ex.getX());
    } catch (IOException ex) {
     Logger.getLogger("mylogger").log(Level.WARNING, "Problem!", ex);
     result = 0;
    }

现在用户可以找到X了!利用这种面向对象的异常设计新异常,代码肯定比你去写一些判断要优雅多了。
0 0
原创粉丝点击