When a parent class declares to throw a checked exception, subclasses have to throw at least the same checked exceptions to fulfill the contract of the parent class. The other way round, a child class method does not have to be declared to throw any exception, but it can't be declared to throw a checked exception that the parent class method is not declared to throw.
To illustrate this, lets imagine you have the following class:
package test;
import java.io.IOException;
public class Parent {
void foo() throws IOException {
throw new IOException();
}
}
This would compile:
package test;
class Child1 extends Parent {
void foo() {
}
}
But this would not:
package test;
import org.xml.sax.SAXException;
class Child2 extends Parent
{
void foo() throws SAXException {
throw new SAXException();
}
}
The javac
compiler would generate the following output:
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
In other words, you can't write this:
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException, SAXException {
super.doGet(req, resp);
...
}
You have to handle the SAXException
in the doGet()
method and to wrap it in a ServletException
if you want to rethrow it.
@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
...
}
}