Java Exception Exception Exception and IOException Exception

The following code compiles fine even if the try block does not actually throw an exception.

public static void main(String[] args) { try {} catch (Exception e) {} // compiles ok } 

But if the catch is replaced by a subclass of Exception, the code will not compile.

 public static void main(String[] args) { try {} catch (IOException e) {} // won't compile. } 

Compiler Error: Inaccessible catch block to throw an IOException. This exception is never thrown from the body of a try statement.

How does this happen when exceptions and an IOException are thrown by exceptions? I am using Java 7.

+5
source share
3 answers

The compiler can know exactly what part of the code can IOException , because it is a checked exception, so every method that can throw such an exception must indicate it in the method signature.

On the other hand, execution pending or unchecked exceptions are not expected, and since RuntimeException (the parent class of excluded exceptions) also extends the Exception class, then the compiler is fine with it.

+6
source

Exception has subclasses that are uncommitted exceptions ( RuntimeException extends Exception ). Throwable will behave in a similar way. RuntimeException or subclasses of RuntimeException will behave similarly. Exception subclasses other than RuntimeException will not.

+3
source

Manouti's answer seems to be correct, but according to the java documentation:

This is a compile-time error if the checked E1 exception type is flagged in the catch clause, but there is no E2 exception type for which all of the following operations are performed:

E2 <: E1 A try block that matches the catch clause can call E2. There is no previous catch block that immediately includes a try statement that catches E2 or the supertype E2. if E1 is not an exception to the class.

There is a clear case for throwing an Exception instance (the Exception class is exceptional, you might say). This is Java 5 documentation, but unless someone sees otherwise, I highly doubt it has changed since

Looking at inheritance tree for Exception and IOException

https://docs.oracle.com/javase/7/docs/api/java/lang/Exception.html

and

https://docs.oracle.com/javase/7/docs/api/java/io/IOException.html?is-external=true

in Java 7, I don’t see that the discussion of Checked / Unchecked exceptions is directly relevant - while it is true that the excepted exceptions do not follow the same rules, unchecked exceptions should inherit from RuntimeException , which of course is no Exception (it is the parent this class)

https://docs.oracle.com/javase/specs/jls/se5.0/html/classes.html#308526

(again, Java 5 docs, but it hasn't changed) https://docs.oracle.com/javase/specs/jls/se5.0/html/exceptions.html

+3
source

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


All Articles