exception handling in the implemented method

前端 未结 1 1952
Happy的楠姐
Happy的楠姐 2021-01-26 05:18

The code below gives a checked error to throws Exception:

import java.io.IOException;

interface some {
    void ss99() throws IOException;
}

publi         


        
1条回答
  •  醉梦人生
    2021-01-26 06:17

    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.

    0 讨论(0)
提交回复
热议问题