子类覆写父类的方法时,如果父类的方法进行了异常声明了,子类可以不理会这个声明,不需要进行异常声明。
package com.vitamin.Console;
import java.lang.Throwable;
public class exceptionTest
{
public static void main(String[] args) throws Exception
{
// TODO Auto-generated method stub]
derive d = new derive();
d.process();
}
}
class myException extends Exception
{
myException()
{
super();
}
}
class base
{
public base()
{
}
public void process() throws myException
{
System.out.println("process() in base class");
throw new myException();
}
}
class derive extends base
{
public derive()
{
super();
}
public void process()
{
System.out.println("process() in derived class");
}
}
2.如果你先用父类catch掉了异常,那子类异常的catch块就不能到达,编译器就会报错:
package com.vitamin.Console;
import java.lang.Throwable;
public class exceptionTest
{
public static void main(String[] args) throws Exception
{
// TODO Auto-generated method stub]
try
{
throw new exception2();
}
catch(myException ex)
{
System.err.println(ex.getMessage().toString());
}
catch(exception2 ex)
{
System.err.println(ex.getMessage().toString());
}
}
}
class myException extends Exception
{
myException()
{
super();
}
}
class exception2 extends myException
{
public exception2()
{
super();
}
}
这种用法编译器是会报错的,应该用防止父类屏蔽掉子类异常处理。
本文转自Phinecos(洞庭散人)博客园博客,原文链接:http://www.cnblogs.com/phinecos/archive/2006/06/16/427782.html,如需转载请自行联系原作者