我们说我有以下内容:
public interface Foo {
...
}
public class Gin {
...
}
public class Fizz {
...
}
public class Buzz {
public Foo getAFoo() {
...
}
public void test() {
Foo myfoo = getAFoo();
if (myFoo instanceof Bar) {
Bar myBar = (Bar) myFoo;
//do something more
} else {
//throw new something exception
}
}
}
这是合理的编程吗?是否存在test()可以抛出的内置异常,还是应该为此创建自己的异常类?
答案 0 :(得分:4)
虽然有点基于意见,但是当对象不是预期类型时抛出的常见异常是ClassCastException
,并且这种方法在JDK中使用相当广泛。你可以比JDK更好,并提供一条消息:
throw new ClassCastException("Object was not of type Bar");
如果对象作为参数传递,您可以使用IllegalArgumentException
,也可以使用以下消息:
throw new IllegalArgumentException("myParameter was not of type Bar");
答案 1 :(得分:2)
关于你的问题:
这是合理的编程吗? 您有机会按照http://www.tutorialspoint.com/design_pattern/strategy_pattern.htm所述使用策略模式。
它将删除您对if和else检查的需要,而是注入适当类型的对象(实现相同的接口)并调用相应的方法。它还将确保您不需要使用另一个if else块来更改您的代码,基本上是关闭open以进行修改。
如果您想坚持上面的代码,可以抛出IllegalArgumentException。
答案 2 :(得分:0)
首先,这是一个编译时错误。
你会得到类似的东西:
error: incompatible types: Bar cannot be converted to Foo
因为interface Foo
不是来自extend
Bar
所以毫无疑问是为它抛出异常。
但是,如果您只是 IMAGINE ,Java
中任何此类事情都是合法的,您必须创建自定义例外。因为没有专门针对此类错误的内置异常类。