简体   繁体   中英

exception handling in the implemented method

The code below gives a checked error to throws Exception :

import java.io.IOException;

interface some {
    void ss99() throws IOException;
}

public class SQL2 implements some {
    @Override
    public void ss99 () throws Exception {}
// ...
}

while the one below compiles fine:

import java.io.IOException;

interface some {
    void ss99() throws IOException;
}

public class SQL2 implements some {
    @Override
    public void ss99 () throws NullPointerException {}
// ...
}

On what logic is Java doing this-- any ideas?

TIA.

The throws keyword indicates that a method or constructor can throw an exception, although it doesn't have to.

Let's start with your second snippet

interface some {
    void ss99() throws IOException;
}

public class SQL2 implements some {
    @Override
    public void ss99 () throws NullPointerException {}
}

Consider

some ref = getSome();
try {
    ref.ss99();
} catch (IOException e) {
    // handle
}

All you have to work with is with your interface some . We (the compiler) don't know the actual implementation of the object it is referencing. As such, we have to make sure to handle any IOException that may be thrown.

In the case of

SQL2 ref = new SQL2();
ref.ss99();

you're working with the actual implementation. This implementation guarantees that it will never throw an IOException (by not declaring it). You therefore don't have to deal with it. You also don't have to deal with NullPointerException because it is an unchecked exception.


Regarding your first snippet, slightly changed

interface some {
    void ss99() throws IOException;
}

public class SQL2 implements some {
    @Override
    public void ss99 () throws Exception { throw new SQLException(); }
}

Consider

some ref = new SQL2();
try {
    ref.ss99();
} catch (IOException e) {
    // handle
}

So although you are handling the exception declared in the interface, you would be letting a checked exception, SQLException , escape unhandled. The compiler cannot allow this.

An overriden method must be declared to throw the same exception (as the parent) or one of its subclasses.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM