scjp - Java unreachable catch block compiler error -


why in java can catch exception if not thrown, can't catch it's subclass (except "unchecked" runtimeexceptions , subclasses). example code:

class test {     public static void main(string[] args) {         try {             // nothing         } catch (exception e) {             // ok                    }          try {             // nothing         } catch (ioexception e) {                // compiler error: unreachable catch block ioexception.                //this exception never thrown try statement body         }            } } 

any ideas?

a runtimeexception thrown any code. in other words, compiler can't predict kind of code can throw it. runtimeexception can caught catch(exception e) block.

ioexception, however, checked exception - method calls declared throw can so. compiler can (reasonably) confident can't possible occur unless there method calls declared throw it.

the java compiler doesn't consider "there's no code @ within try block" situation - allows catch unchecked exceptions, in reasonable scenarios there code could potentially throw unchecked exception.

from section 14.21 of jls:

a catch block c reachable iff both of following true:

  • some expression or throw statement in try block reachable , can throw exception type assignable parameter of catch clause c. (an expression considered reachable iff innermost statement containing reachable.)
  • there no earlier catch block in try statement such type of c's parameter same or subclass of type of a's parameter.

arguably compiler should realize there no expressions within try block in first case... looks still unreachable catch clause, me.

edit: noted in comments, section 14.20 contains this:

it compile-time error if catch clause catches checked exception type e1 there exists no checked exception type e2 such of following hold:

  • e2 <: e1
  • the try block corresponding catch clause can throw e2
  • no preceding catch block of enclosing try statement catches e2 or supertype of e2.

unless e1 class exception.

so looks that's you're actually running foul of, spec isn't clear in terms of unreachable catch blocks in 14.21.


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -