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

前端 未结 6 1336
忘掉有多难
忘掉有多难 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:22

    It can happen, even with checked exceptions. And sometimes it can break logging.

    Suppose a library method uses this trick to allow an implementation of Runnable that can throw IOException:

    class SneakyThrowTask implements Runnable {
    
        public void run() {
            throwSneakily(new IOException());
        }
    
        private static RuntimeException throwSneakily(Throwable ex) {
            return unsafeCastAndRethrow(ex);
        }
    
        @SuppressWarnings("unchecked")
        private static X unsafeCastAndRethrow(Throwable ex) throws X {
            throw (X) ex;
        }
    
    }
    

    And you call it like this:

    public static void main(String[] args) {
        try {
            new SneakyThrowTask().run();
        } catch (RuntimeException ex) {
            LOGGER.log(ex);
        }
    }
    

    The exception will never be logged. And because it's a checked exception you cannot write this:

    public static void main(String[] args) {
        try {
            new SneakyThrowTask().run();
        } catch (RuntimeException ex) {
            LOGGER.log(ex);
        } catch (IOException ex) {
            LOGGER.log(ex); // Error: unreachable code
        }
    }
    

提交回复
热议问题