在这种情况下,我会写成:
public Object getClone(SomeInterface a) throws TotallyFooException {
if (a == null) {
throw new TotallyFooException() ; }
else {
try {
return a.someMethod(); }
catch (SomeException e) {
throw new IllegalArgumentException(e) ; } }
}
有趣的是,你说“try语句永远不会失败”,但你仍然费心编写了一条语句
e.printStackTrace();
,声称这条语句永远不会被执行。为什么?
也许你对此并没有坚定的信念。在我看来这是好事,因为你的信念并不是基于你编写的代码,而是基于你的客户不会违反前提条件的期望。最好为公共方法进行防御式编程。
顺便说一下,你的代码在我这里无法编译。即使a的类型为Cloneable,你也不能调用
a.clone()
。至少Eclipse的编译器是这样说的。表达式
a.clone()
会出错:
The method clone() is undefined for the type Cloneable
针对你的特定情况,我会这样做:
public Object getClone(PubliclyCloneable a) throws TotallyFooException {
if (a == null) {
throw new TotallyFooException(); }
else {
return a.clone(); }
}
其中PubliclyCloneable
的定义如下:
interface PubliclyCloneable {
public Object clone() ;
}
或者,如果您绝对需要参数类型为Cloneable
,则以下代码至少可以编译通过。
public static Object getClone(Cloneable a) throws TotallyFooException {
if (a == null) {
throw new TotallyFooException(); }
else {
try {
return a.getClass().getMethod("clone").invoke(a) ; }
catch( IllegalAccessException e ) {
throw new AssertionError(null, e) ; }
catch( InvocationTargetException e ) {
Throwable t = e.getTargetException() ;
if( t instanceof Error ) {
throw (Error) t ; }
else if( t instanceof RuntimeException ) {
throw (RuntimeException) t ; }
else {
throw new IllegalArgumentException(t) ; } }
catch( NoSuchMethodException e ) {
throw new AssertionError(null, e) ; } }
}
AssertionError
而不是InternalError
。后者似乎是用于特殊情况,如果 JVM 中出现问题。而你基本上断言代码不会被执行到。 - kap