Skip to content

Latest commit

 

History

History
49 lines (34 loc) · 1.36 KB

2862.md

File metadata and controls

49 lines (34 loc) · 1.36 KB

Back to questions

2862: Exceptions and inheritance (ii)

Consider the following Java classes:

MyExceptionC.java

MyExceptionD.java

A.java

B.java

These classes compile, even though foo() in B throws a different exception from foo() in A. Explain why the classes compile despite this difference.

Suppose we removed @Override from foo() in B, added

import java.io.IOException;

to the top of class B and changed the declaration of foo() in B to:

void foo() throws IOException {
  throw new IOException();
}

Would the classes still compile? What does your answer tell you about the role of exceptions in method overloading in Java?

Finally, with the original set of classes, suppose we added this demo class:

public class Demo {
  public static void main(String[] args) {
    A myB = new B();
    try {
      myB.foo();
    } catch (MyExceptionD e) {
      System.out.println("Exception of type MyExceptionD was thrown.");
    }
  }
}

Explain why this class will fail to compile. Explain what simple change you can make to Demo to solve the problem.