Java exception handling with method overriding

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.
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容