今天在论坛上看到一个关于异常的问题,没看到一个正确的回帖,也许好多朋友还搞不懂这个问题,特引用过来一下:
---------------------------------------
Imagine that there are two exception classes called Exception1 and Exception2 that descend from the Exception class. Given these two class definitions,
1. class First {
2. void test() throws 1, Exception2 { . . . }
3. }
4. class Second extends First {
5. void test() { . . . }
Create a class called Third that extends Second and defines a test() method. What exceptions can Third's test method throw?
answer:no checked Exception .why?
这个答案和any Exception有什么不同,哪位高手帮忙解释一下,
-------------------------------------
1。首先要清楚异常的分类,异常分为运行时异常(RuntimeException)和
受检查异常(Checked Exception).
运行时异常(RuntimeException):是指程序员由于自己的错误而造成
的可避免异常。比如下标越界异常:ArrayIndexOutOfBoundsException,
这是程序员在Code的时候就能够正常处理的,还比如除数为0时的
ArithmeticException。
受检查异常(Checked Exception):是指非人为原因而造成的不可避
免的异常,比如IOException,SQLException,ClassNotFoundException...
这些异常并不是由于我们程序员自己的粗心和错误而造成的。这类异常必须
要用try...catch来捕获或者声明抛出异常。在编译时JVM会检查的,而
运行时异常(RuntimeException)在编译的时候JVM是不会检查的。
2。我们在方法重写时所说的子类不能抛出比父类更多的异常,这里所说的异常并
不是所有异常(any Exception),而只是受检查异常(Checked Exception),
并不适应运行时异常(RuntimeException),比如下面这个例子:
class Sup
{
public void A() throws ArithmeticException
{
}
}
class Sub extends Sup
{
public void A() throws RuntimeException
{
}
}
在上面这个例子中在重写父类的A()方法时抛出的异常RuntimeException是
ArithmeticException的父类,也许有些朋友以为这是错误的,肯定编译不过,
但是我很明确的告诉你上面的代码是正确的,原因见以上所述。不信的朋友
可以自己动手编译一下了。
看完我上面的解释,大家应该知道答案no checked Exception就是我所
说的运行时异常(RuntimeException)。不能是所有异常(any Exception),
当然还可以是Exception1和Exception2,或者是它们的子类,只要有这个答案的话。