子類覆寫父類的方法時,如果父類的方法進行了異常聲明了,子類可以不理會這個聲明,不需要進行異常聲明。
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()
public void process()
System.out.println("process() in derived class");
2.如果你先用父類catch掉了異常,那子類異常的catch塊就不能到達,編譯器就會報錯:
try
{
throw new exception2();
}
catch(myException ex)
System.err.println(ex.getMessage().toString());
catch(exception2 ex)
class exception2 extends myException
public exception2()
這種用法編譯器是會報錯的,應該用防止父類屏蔽掉子類異常處理。
本文轉自Phinecos(洞庭散人)部落格園部落格,原文連結:http://www.cnblogs.com/phinecos/archive/2006/06/16/427782.html,如需轉載請自行聯系原作者