我应该声明方法签名中的方法抛出的所有异常,还是异常的超类? [英] Should I declare all exceptions thrown from a method in the method signature or just the super class of the exceptions?

查看:421
本文介绍了我应该声明方法签名中的方法抛出的所有异常,还是异常的超类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我从方法中抛出检查的异常时,我应该在方法签名或所有不同类型中声明超类的异常?如果我有以下例外:

  private class SuperException extends Exception {

}

private class SubExceptionOne extends SuperException {

}

private class SubExceptionTwo extends SuperException {

}

如果方法签名为:

  void confirmAccount()throws SubExceptionOne,SubExceptionTwo; 

  void confirmAccount()throws SuperException; 

在最后的方法签名中,如何告诉其他开发人员可以从方法中抛出什么异常?如果不同的子类型需要不同的处理方式?

解决方案

接口应尽可能稳定。所以可能超级许多图书馆使用超级策略,因为异常规范比可读性或安全性增加了更多的可维护性。即使IOException是一个Super,几乎所有的Java库代码都使用,而不是声明更具体的异常。 (但是当他们声明更具体的例外,这是因为合同是更普遍的IOExceptions不会被抛出。)



您可能会列出Sub1和Sub2如果你真的想说出每一个例外都可以抛出,但是不想说Super的任何派生都可以抛出来。也许Sub1是NumberCrunchException,你的方法调用crunchNumbers(),你的方法的用户可以放心,这是你的方法唯一的例外。在这种情况下,具体策略更好。


When I throw checked exceptions from a method should I just declare the super class of the exceptions in the method signature or all the different types? If I have the following exceptions:

private class SuperException extends Exception {

}

private class SubExceptionOne extends SuperException {

}

private class SubExceptionTwo extends SuperException {

}

Should the method signature be:

 void confirmAccount() throws SubExceptionOne, SubExceptionTwo;

or

 void confirmAccount() throws SuperException;

In the last method signature, how do I tell other developers what exceptions that could be thrown from the method? If the different sub types need different handling?

解决方案

The interface should be as stable as possible. So probably Super. Many libraries use the "Super" strategy, because exception specs cause far more annoyance in maintainability than readability or safety they add. Even the IOException is a Super that nearly all Java library code uses instead of declaring more specific exceptions. (But when they do declare more specific exceptions, it's because the contract is that more general IOExceptions won't be thrown. Read on.)

You might list Sub1 and Sub2 if you really do want to say each of those exceptions can be thrown, but don't want to say that any derivative of Super can be thrown. Perhaps Sub1 is NumberCrunchException and your method calls crunchNumbers() and users of your method can be assured that's the only exception-ful thing your method does. In that case the specific strategy is better.

这篇关于我应该声明方法签名中的方法抛出的所有异常,还是异常的超类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆