java - Effects of Try/Catch against Throwing Exceptions in a constructing class' constructor -
i playing around of code , came across didn't understand. have class called sentimentclassifier, constructor of looks this:
public sentimentclassifier(final int ngramtobeused) { try { classifier = (dynamiclmclassifier<?>) abstractexternalizable.readobject(new file(etc)); } catch (classnotfoundexception e) { e.printstacktrace(); } catch (ioexception e) { e.printstacktrace(); } }
i have class creates one, so:
public twittermanager(final int ngramtobeused) { sentimentclassifier = new sentimentclassifier(ngramtobeused); }
if run code this, works fine. if change first class using try/catch
throw
exception, so:
public sentimentclassifier(final int ngramtobeused) throws classnotfoundexception, ioexception { classifier = (dynamiclmclassifier<?>) abstractexternalizable.readobject(new file(etc)); }
suddenly second class complains ioexception
isn't being handled. why thrown thrown
exception , not try/catch
?
when call method m1
method m2
:
if code in
m1
raises checked exception, , methodm1
handles it, rather throwing it, don't have worry exception while calling it.now, if exception raised in
m1
, not being handled inm1
itself, rather propagated stack trace,m1
must declare exception in throws clause. convenience of calling method know should ready handle exception in case thrown. case checked exception.but if calling method
m2
, doesn't handle exception, has option re-declare exception thrown in it's own throws clause, in case exception propagated further stack trace.if method
m2
neither of previous 2 task, compiler error. because haven't given proper path or way handle exception can thrown.
note above arguments true checked exception only. unchecked exception, don't need handle yourself, neither need declare in throws clause.
suggested read:
Comments
Post a Comment