我在Java是这里抛出的异常吗?
public class PolyTest
{
public static void main(String... arg)
{
Animal a = new Animal();
Horse b = new Horse();
Animal c = new Horse();
a.eat();
b.eat();
c.eat();
}
}
class Animal
{
public void eat() throws IndexOutOfBoundsException
{
System.out.println("Animal Eating");
}
}
class Horse extends Animal
{
@Override
public void eat()
{
System.out.println("Horse Eating");
}
}
有这个程序现在,令人惊讶它的工作原理没有,尽管没有try catch块的任何错误或抛出子句中的主要方法。
1.为什么a.eat()
在主要方法中没有给出任何错误?
2.当我将IndexOutOfBoundsException
更改为Exception
时,这是编译时错误。为什么?
在kathy sierra的SCJP考试指南中阅读了这篇文章,但无法理解这里的概念。
IndexOutOfBoundsException是一个RuntimeException,因此它不需要特殊处理。 – wxyz
IndexOutOfBoundsException是一个RuntimeException。请参阅http://stackoverflow.com/questions/2190161/difference-between-java-lang-runtimeexception-and-java-lang-exception。 – jarmod
可能的重复[运行时异常没有编译错误。为什么?](http://stackoverflow.com/questions/6150609/no-compilation-error-on-runtime-exceptions-why) – Mat