Why can I declare a function without the keyword "throws"?

Consider the following code:

public interface I1 {
 public void bar1() throws IOException; 
} 

public interface I2 extends I1 { 
 public void bar2() throws Exception; 
} 

public interface I3 { 
 public void bar3() throws Exception; 
} 

public abstract class A implements I2 { 
 public void bar2() throws Exception{}; 
 public void bar3() throws Exception{}; 
 protected abstract void bar4(); 
 protected void bar5() {}; 
}

Now I created the class Bas follows:

public class B extends A implements I3 {

    @Override
    protected void bar4() {}

    public void bar1()  {}

}

Why does the compiler allow me to do this? I mean, it should not be:
public void bar1() throws IOException;

+4
source share
2 answers

When overriding, you cannot throw a wider or new exception. Superclass method exception exceptions are allowed.

, , , . , , FileNotFoundException, , SQLException, , FileNotFoundException.

+1

.

, , , .

, super, .

, :

new B().bar1() 

, , .

((A)new B()).bar1()

, A A, .

, C:

public class C extends A implements I3 {

    @Override
    protected void bar4() {}

    public void bar1() throws IOException, SomeOtherException {}

}

, , C A, SomeOtherException.

+1

Source: https://habr.com/ru/post/1547018/


All Articles