Why doesn't catching Exception catch RuntimeException?

后端 未结 5 725
眼角桃花
眼角桃花 2020-12-08 00:05

This is very odd to me. RuntimeException inherits from Exception, which inherits from Throwable.

catch(Exception exc)          


        
5条回答
  •  無奈伤痛
    2020-12-08 00:47

    The premise of the question is flawed, because catching Exception does catch RuntimeException. Demo code:

    public class Test {
        public static void main(String[] args) {
            try {
                throw new RuntimeException("Bang");
            } catch (Exception e) {
                System.out.println("I caught: " + e);
            }
        }
    }
    

    Output:

    I caught: java.lang.RuntimeException: Bang
    

    Your loop will have problems if:

    • callbacks is null
    • anything modifies callbacks while the loop is executing (if it were a collection rather than an array)

    Perhaps that's what you're seeing?

提交回复
热议问题