當父類聲明拋出一個檢查的異常時,子類必須至少拋出相同的檢查異常來完成父類的契約。反過來說,子類方法不必聲明爲拋出任何異常,但不能聲明拋出一個檢查的異常,即父類方法未聲明爲拋出。
爲了說明這一點,讓我們假設你有以下類:
package test;
import java.io.IOException;
public class Parent {
void foo() throws IOException {
throw new IOException();
}
}
這將編譯:
package test;
class Child1 extends Parent {
void foo() {
}
}
但這並不:
package test;
import org.xml.sax.SAXException;
class Child2 extends Parent
{
void foo() throws SAXException {
throw new SAXException();
}
}
的javac
編譯器會生成以下輸出:
test/Child2.java:6: foo() in test.Child2 cannot override foo() in test.Parent; overridden method does not throw org.xml.sax.SAXException
void foo() throws SAXException {
^
1 error
換句話說,你不能這樣寫:
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException, SAXException {
super.doGet(req, resp);
...
}
你必須處理在doGet()
方法SAXException
,如果你想重新拋出來包裝它在一個ServletException
。
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
super.doGet(req, resp);
try {
// code that possibly throws a SAXException
...
} catch (SAXException e) {
// handle it or rethrow it as ServletException
...
}
}
這是對我所說的(很多)更好的解釋。 – 2009-12-01 12:39:29