Is there a way to make Runnable's run() throw an exception?

前端 未结 9 1243
忘了有多久
忘了有多久 2020-12-07 14:43

A method I am calling in run() in a class that implements Runnable) is designed to be throwing an exception.

But the Java compiler won\'t let me do that and suggests

9条回答
  •  星月不相逢
    2020-12-07 15:29

    @FunctionalInterface
    public interface CheckedRunnable extends Runnable {
    
        @Override
        default void run() throws RuntimeException {
            try {
                runThrows();
            }
            catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        }
    
        void runThrows() throws E;
    
    }
    

提交回复
热议问题