Java compile-time exception excluded

Exceptionand IOExceptionboth are compile-time-dependent exceptions.

But we cannot use IOExceptionin the catch block. But we can use Exceptionin the catch block, what is the reason for this.

    import java.io.*;
    class Demo{
        public static void main(String args[]){
            try{

            }catch(IOException e){ // Does not compile

            }

            try{

            }catch(Exception e){ // Compile

            }
        }
    }
+4
source share
3 answers

You cannot catch a checked exception that is never thrown into a try block other than Exception(or Throwable). This behavior is defined by JLS, section 11.2.3 :

, catch E1, , try, catch, , E1, E1 .

+8

, , IOException ... , Exception, , IOException, RuntimeException .. catching, RuntimeException , , . IOException - , , , , , , .

0

See, the main reason is that you can catch any RuntimeException, it doesn't matter if it is selected from the try block or not, and RuntimeException is a class that extends the Exception class. So, as a parent class, catch "Exception" is always allowed. In your case, an exception thrown by an IOException is only allowed if you try to block the probability of it being thrown.

0
source

Source: https://habr.com/ru/post/1606460/


All Articles