i have been trying find out answer question did not satisfactory explanation. here background:
java 7 allows catch multiple exceptions in single catch block provided exceptions diffrent hierarchy. eg:
try { // code } catch(sqlexception | filenotfoundexception e) { e.printstacktrace(); } catch(exception e) { e.printstacktrace(); }
but if exceptions same hierarchy must use multiple catch blocks like:
try { // code } catch(filenotfoundexception e) { e.printstacktrace(); } catch(ioexception e) { e.printstacktrace(); }
but if try write code below compiler complains "the exception filenotfoundexception
caught alternative ioexception
"
try { // code } catch(filenotfoundexception | ioexception e) { // compiler error e.printstacktrace(); }
now question is: why compiler reports error in last case, can't figure out filenotfoundexception
special case of ioexception
? save code duplication when exception handling logic same.
why compiler reports error in last case, can't figure out
filenotfoundexception
special case ofioexception
?
because filenotfoundexception
subclass of ioexception
. in other words, "filenotfoundexception |
" part redundant.
the reason why code below ok...
} catch(filenotfoundexception e) { ... } catch(ioexception e) { ... }
...is because here ioexception
clause matters: if socketexception
thrown instance, pass filenotfoundexception
part, , caught in ioexception
clause.
Comments
Post a Comment