What happens if a method throws an exception that was not specified in the method declaration with “throws”

前端 未结 6 1325
忘掉有多难
忘掉有多难 2021-01-01 11:27

I\'ve never used the \"throws\" clause, and today a mate told me that I had to specify in the method declaration which exceptions the method may throw. However, I\'ve been u

6条回答
  •  北海茫月
    2021-01-01 12:13

    If a method is declared with the throws keyword then any other method that wishes to call that method must either be prepared to catch it or declare that itself will throw an exception.

    For instance if you want to pause the application you must call Thread.sleep(milliseconds);

    But the declaration for this method says that it will throw an InterruptedException

    Declaration:

    public static void sleep(long millis) throws InterruptedException
    

    So if you wish to call it for instance in your main method you must either catch it:

    public static void main(String args[]) {
        try {
            Thread.sleep(1000);
        } catch(InterruptedException ie) {
            System.out.println("Opps!");
        }
    }
    

    Or make the method also declare that it is throwing an exception:

    public static void main(String args[]) throws InterruptedException {
        Thread.sleep(1000);
    }
    

提交回复
热议问题