Java unreachable catch block compiler error

后端 未结 6 1084
孤城傲影
孤城傲影 2020-11-27 06:25

Why in Java can we catch an Exception even if it is not thrown, but we can\'t catch it\'s subclass (except for \"unchecked\" RuntimeExceptions and

6条回答
  •  日久生厌
    2020-11-27 07:03

    IOException is a checked Exception that is only thrown by IO related code. Since your try block does nothing, nothing IO related will ever happen, IOExceptions will never be thrown, so there is no way the catch block will ever be executed and the compiler don't let you get around with it. As you said, Exception may refer to unchecked Runtime Exceptions that may occur at any moment. That's the main difference between unchecked and checked exceptions, and that is why the compiler don't enforce the code to catch every possible runtime exception.

提交回复
热议问题