谁能告诉我这样的代码,编译为何不会报错?
lass base
{
public void amethod() throws classnotfoundexception
{
}
}
public class derived extends base
{
public void amethod() throws runtimeexception
{
}
}
我这道题目是这样的:
父类base的方法amethod?出一个classnotfoundexception异常
子类derived重写amethod方法并?出一个runtimeexception异常
如果按照java的exception理论,那么应该是:
子类derived的amethod方法要么不?异常,
要么就必须?出classnotfoundexception异常或是classnotfoundexception异常的子类才行.
而runtimeexception并不是classnotfoundexception的子类.
它们没有任何的继承关系.
按照java的exception理论,应该编译不能通过.
但是现在可以编译通过,请问这是为什么?
runtimeexception是自动throws的,不需要declare(decalre了效果也不会有任何变化),即使声明了throws runtime exception,编译器也不会按通常的规则处理。所以上述代码的等效形式是:
class base
{
public void amethod() throws classnotfoundexception
{
}
}
public class derived extends base
{
public void amethod()
{
}
}
****** 答案 *****
java中的异常可以分为3种类型:
1。从exception类直接派生出来的异常类
2。运行时刻类(runtimeexception)
3。i/o异常类
你说的那个理论对于1,3成立,但是runtimeexception是没有必要去catch的.(www.itpub.net)
闽公网安备 35060202000074号