Java

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:

上一篇下一篇

猜你喜欢

热点阅读