Why can't overriding methods throw exceptions

2019-01-01 01:50发布

I was going through SCJP 6 book by Kathe sierra and came across this explanations of throwing exceptions in overridden method. I quite didn't get it. Can any one explain it to me ?

The overriding method must NOT throw checked exceptions that are new or broader than those declared by the overridden method. For example, a method that declares a FileNotFoundException cannot be overridden by a method that declares a SQLException, Exception, or any other non-runtime exception unless it's a subclass of FileNotFoundException.

标签: java
14条回答
人间绝色
2楼-- · 2019-01-01 02:28

The subclass's overriding method can only throw multiple checked exceptions that are subclasses of the superclass's method's checked exception, but cannot throw multiple checked exceptions that are unrelated to the superclass's method's checked exception

查看更多
浪荡孟婆
3楼-- · 2019-01-01 02:29

To illustrate this, consider:

public interface FileOperation {
  void perform(File file) throws FileNotFoundException;
}

public class OpenOnly implements FileOperation {
  void perform(File file) throws FileNotFoundException {
    FileReader r = new FileReader(file);
  }
}

Suppose you then write:

public class OpenClose implements FileOperation {
  void perform(File file) throws FileNotFoundException {
    FileReader r = new FileReader(file);
    r.close();
  }
}

This will give you a compilation error, because r.close() throws an IOException, which is broader than FileNotFoundException.

To fix this, if you write:

public class OpenClose implements FileOperation {
  void perform(File file) throws IOException {
    FileReader r = new FileReader(file);
    r.close();
  }
}

You will get a different compilation error, because you are implementing the perform(...) operation, but throwing an exception not included in the interface's definition of the method.

Why is this important? Well a consumer of the interface may have:

FileOperation op = ...;
try {
  op.perform(file);
}
catch (FileNotFoundException x) {
  log(...);
}

If the IOException were allowed to be thrown, the client's code is nolonger correct.

Note that you can avoid this sort of issue if you use unchecked exceptions. (I am not suggesting you do or don't, that is a philosophical issue)

查看更多
与君花间醉酒
4楼-- · 2019-01-01 02:32

The overriding method CAN throw any unchecked (runtime) exception, regardless of whether the overridden method declares the exception

Example:

class Super {
    public void test() {
        System.out.println("Super.test()");
    }
}

class Sub extends Super {
    @Override
    public void test() throws IndexOutOfBoundsException {
        // Method can throw any Unchecked Exception
        System.out.println("Sub.test()");
    }
}

class Sub2 extends Sub {
    @Override
    public void test() throws ArrayIndexOutOfBoundsException {
        // Any Unchecked Exception
        System.out.println("Sub2.test()");
    }
}

class Sub3 extends Sub2 {
    @Override
    public void test() {
        // Any Unchecked Exception or no exception
        System.out.println("Sub3.test()");
    }
}

class Sub4 extends Sub2 {
    @Override
    public void test() throws AssertionError {
        // Unchecked Exception IS-A RuntimeException or IS-A Error
        System.out.println("Sub4.test()");
    }
}
查看更多
大哥的爱人
5楼-- · 2019-01-01 02:32

Java is giving you the choice to restrict exceptions in the parent class, because it's assuming the client will restrict what is caught. IMHO you should essentially never use this "feature", because your clients may need flexibility down the road.

Java is an old language that is poorly designed. Modern languages don't have such restrictions. The easiest way around this flaw is make your base class throw Exception always. Clients can throw more specific Exceptions but make your base classes really broad.

查看更多
春风洒进眼中
6楼-- · 2019-01-01 02:33

The overriding method must NOT throw checked exceptions that are new or broader than those declared by the overridden method.

This simply means when you override an existing method, the exception that this overloaded method throws should be either the same exception which the original method throws or any of its subclasses.

Note that checking whether all checked exceptions are handled is done at compile time and not at runtime. So at compile time itself, the Java compiler checks the type of exception the overridden method is throwing. Since which overridden method will be executed can be decided only at runtime, we cannot know what kind of Exception we have to catch.


Example

Let's say we have class A and its subclass B. A has method m1 and class B has overridden this method (lets call it m2 to avoid confusion..). Now let's say m1 throws E1, and m2 throws E2, which is E1's superclass. Now we write the following piece of code:

A myAObj = new B();
myAObj.m1();

Note that m1 is nothing but a call to m2 (again, method signatures are same in overloaded methods so do not get confuse with m1 and m2.. they are just to differentiate in this example... they both have same signature). But at compile time, all java compiler does is goes to the reference type (Class A in this case) checks the method if it is present and expects the programmer to handle it. So obviously, you will throw or catch E1. Now, at runtime, if the overloaded method throws E2, which is E1's superclass, then ... well, it's very wrong (for the same reason we cannot say B myBObj = new A()). Hence, Java does not allow it. Unchecked exceptions thrown by the overloaded method must be same, subclasses, or non-existent.

查看更多
余欢
7楼-- · 2019-01-01 02:35

The overriding method must NOT throw checked exceptions that are new or broader than those declared by the overridden method.

Example:

class Super {
    public void throwCheckedExceptionMethod() throws IOException {
        FileReader r = new FileReader(new File("aFile.txt"));
        r.close();
    }
}

class Sub extends Super {    
    @Override
    public void throwCheckedExceptionMethod() throws FileNotFoundException {
        // FileNotFoundException extends IOException
        FileReader r = new FileReader(new File("afile.txt"));
        try {
            // close() method throws IOException (that is unhandled)
            r.close();
        } catch (IOException e) {
        }
    }
}

class Sub2 extends Sub {
    @Override
    public void throwCheckedExceptionMethod() {
        // Overriding method can throw no exception
    }
}
查看更多
登录 后发表回答