How can Java programs crash when exceptions must always be caught? -
this question has answer here:
forgive me if stupid question, far know, java exceptions must caught , handled. example, create compiler error:
public string foo(object o) { if (o instanceof boolean) { throw new exception(); } return o.tostring(); }
because method foo()
didn't add throws
clause.
however, example work (unless either method foo()
didn't have throws
clause or method bar()
didn't surround usage of foo()
in try/catch
block):
public string foo(object o) throws exception { if (o instanceof boolean) { throw new exception(); } return o.tostring(); } public void bar(object o) { try { string s = foo(o); } catch (exception e) { //... } //... }
at end, java program still crashes due unhandled exception.
how happen?
you don't have handle all kinds of exceptions.
exceptions inherit java.lang.runtimeexception
or java.lang.error
so-called unchecked exceptions can caught try-catch construct, don't have be, though.
as can see in api docs of java.lang.error
, not inherit java.lang.exception
. reason, not caught try-catch block - java.lang.exception
, subclasses.
have @ this article in docs.
Comments
Post a Comment