Java exception handling with met
2019-11-01 本文已影响0人
JaedenKil
Scenario 1. If the super class does not declare an exception:
1.1 The sub class declares a checked exception
class SuperClass {
void foo() {
}
}
import java.io.IOException;
class SubClass extends SuperClass {
@Override
void foo() throws IOException {
}
}
// overridden method does not throw 'java.io.IOException'
1.1 The sub class declares a unchecked exception
class SuperClass {
void foo() {
}
}
class SubClass extends SuperClass {
@Override
void foo() throws ArithmeticException {
}
}
// Okay
Scenario 2. If the super class declares an exception:
2.1 The sub class declares a exception other than the child exception of the super class exception
class SuperClass {
void foo() throws RuntimeException {
}
}
import java.io.IOException;
class SubClass extends SuperClass {
@Override
void foo() throws IOException {
}
}
// overridden method does not throw 'java.io.IOException'
2.2 The sub class declares a child exception of the super class exception
class SuperClass {
void foo() throws RuntimeException {
}
}
class SubClass extends SuperClass {
@Override
void foo() throws ArithmeticException {
}
}
// Okay
2.3 The sub class does not declare exception
class SuperClass {
void foo() throws RuntimeException {
}
}
class SubClass extends SuperClass {
@Override
void foo() {
}
}
// Okay
2.4 The sub class declares an unchecked exception
import java.io.IOException;
class SuperClass {
void foo() throws IOException {
System.out.println("This is in super class.");
}
}
class SubClass extends SuperClass {
@Override
void foo() throws ArithmeticException{
System.out.println("This is in sub class.");
}
}
// Okay
Conclusion:
- If Super Class does not declare an exception, then the Sub Class can only declare unchecked exceptions, but not the checked exceptions.
- If SuperClass declares an exception, then the SubClass can only declare the child exceptions of the exception declared by the SuperClass, but not any other exception. Except the following scenario:
- If SuperClass declares a checked exception, the SubClass can declare an unchecked exception.
- If SuperClass declares an exception, then the SubClass can declare without exception.