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.
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容