问题
Given
public class ToBeTestHandleException{
static class A {
void process() throws Exception {
throw new Exception();
}
}
static class B extends A {
void process() {
System.out.println("B ");
}
}
public static void main(String[] args) {
A a = new B();
a.process();
}
}
Why we should handle the exception at line (a.process()) ?.The method process of class B does not throw exception at all? PS:This is an SCJP question.
回答1:
You've assigned your B
instance to a variable of type A
. Since A.process()
throws the exception, your code needs to handle that possibility.
Imagine you pass your instance to another method that accepts A
s:
public void doSomething(A a) {
a.process; // <--- we don't know this is a B, so you are forced to
// catch the exception
}
来源:https://stackoverflow.com/questions/17170583/why-we-must-handle-exception-for-method-not-throwing-exceptions