java - Why is catching checked exceptions allowed for code that does not throw exceptions? -


in java, methods throw checked exceptions (exception or subtypes - ioexception, interruptedexception, etc) must declare throws statement:

public abstract int read() throws ioexception; 

methods not declare throws statement can't throw checked exceptions.

public int read() { // not compile     throw new ioexception(); } // error: unreported exception java.io.ioexception; must caught or declared thrown 

but catching checked exceptions in safe methods still legal in java:

public void safemethod() { system.out.println("i'm safe"); }  public void test() { // method guarantees not throw checked exceptions     try {         safemethod();     } catch (exception e) { // catching checked exception java.lang.exception         throw e; // can throw... checked exception?     } } 

actually, no. it's bit funny: compiler knows e not checked exception , allows rethrow it. things bit ridiculous, code not compile:

public void test() { // guarantees not throw checked exceptions     try {         safemethod();     } catch (exception e) {                 throw (exception) e; // seriously?     } } // error: unreported exception java.lang.exception; must caught or declared thrown 

the first snippet motivation question.

compiler knows checked exceptions can't thrown inside safe method - maybe should allow catch unchecked exceptions?


returning main question - there reasons implement catching checked exceptions in way? flaw in design or missing important factors - maybe backward incompatibilities? potentially go wrong if runtimeexception allowed catched in scenario? examples appreciated.

quoting java language specification, §11.2.3:

it compile-time error if catch clause can catch checked exception class e1 , not case try block corresponding catch clause can throw checked exception class subclass or superclass of e1, unless e1 exception or superclass of exception.

i'm guessing rule originated long before java 7, multi-catches did not exist. therefore, if had try block throw multitude of exceptions, easiest way catch catch common superclass (in worst case, exception, or throwable if want catch errors well).

note may not catch exception type unrelated thrown - in example, catching subclass of throwable not runtimeexception error:

try {     system.out.println("hello"); } catch (ioexception e) {  // compilation error     e.printstacktrace(); } 


edit op: main part of answer fact question examples work exception class. catching checked exceptions not allowed in random places of code. sorry if confused using these examples.


Comments

Popular posts from this blog

jOOQ update returning clause with Oracle -

java - Warning equals/hashCode on @Data annotation lombok with inheritance -

java - BasicPathUsageException: Cannot join to attribute of basic type -