Throw exceptions without needing to use try in Java -
i have java code want able run. should throw exception if have totally been added more 4 strings, should not needed use try/catch first 4 times addstring method called.
foo myfoo = new foo(); myfoo.addstring("string a"); myfoo.addstring("string b"); myfoo.addstring("string c"); myfoo.addstring("string d"); boolean exceptionthrown = false; try { myfoo.addstring("string e"); } catch (noroomformorestringsexception e) { exceptionthrown = true; } asserttrue(exceptionthrown);
if add in addstring function, require me use trow/catch statement.
public void addstring(string str) throws noroomformorestringsexception { ... if(strings.size() >= 4) { throw new noroomformorestringsexception(); }
how can throw exception in addstring method without needing use try/catch statement?
how can throw exception in addstring method without needing use try/catch statement ?
you need declare noroomformorestringsexception
runtimeexception
shown below:
public noroomformorestringsexception extends runtimeexception { //methods custom exception }
in java, exception
objects 2 types:
(1) checked exceptions: these exceptions force try/catch or declare them in method signature (like current noroomformorestringsexception). the best practice need use these checked exceptions i.e., when have got recovery action needs done upon catching exception.
(2) unchecked/runtime exceptions : these exceptions don't force catch or declare exception.
most of times, can prefer using runtime exceptions (type 2 above) because in general, able little (like logging) upon getting exception.
because checked exceptions noisy (means force callers either catch or declare in method signatures), popular frameworks (like spring
) try avoid them i.e., spring
throws runtime exceptions or better wraps/converts checked exceptions (if jdk) runtime exceptions , throws.
so, in short, if have got recovery mechanism, go checked exception (type1 above), otherwise, need go runtimeexception (type2 above)
you can refer here
Comments
Post a Comment