有一種特殊情況,我們不能使用拋出,我們必須使用try-catch。 有一條規則:「重寫的方法不能拋出除父類正在拋出的東西外的其他異常」。如果有任何額外的異常應該使用try-catch處理。 考慮這個代碼片段。 有一個簡單的基類
package trycatchvsthrows;
public class Base {
public void show()
{
System.out.println("hello from base");
}
}
和它的派生類:
package trycatchvsthrows;
public class Derived extends Base {
@Override
public void show() {
// TODO Auto-generated method stub
super.show();
Thread thread= new Thread();
thread.start();
try {
thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// thread.sleep(10);
// here we can not use public void show() throws InterruptedException
// not allowed
}
}
當我們調用Thread.sleep()方法,我們不得不使用的try-catch,在這裏我們不能使用:
public void show() throws InterruptedException
因爲重寫的方法不能拋出額外的異常。
不是一個真正的答案,但你可能會感興趣的斯內德爾德的文章[例外在雨林](http://nedbatchelder.com/text/exceptions-in-the-rainforest.html),這有助於解釋一種情況,其中一種風格或另一種風格是首選。 – 2010-07-13 21:30:13
而不是在catch中有「showException(e)」,你是問你是否在catch中拋出了e(或者根本沒有try/catch)? – MacGyver 2012-01-22 10:51:15