java - Assert vs Exceptions -
i have read information on when use assert , when use exception. unclear me why ?
eg: assertions intended used solely means of detecting programming errors, aka bugs. contrast, exception can indicate other kinds of error or "exceptional" condition; e.g. invalid user input, missing files, heap full , on.
now: "assertions intended used solely means of detecting programming errors, aka bugs "- whats harm asserts replaced exceptions ? exceptions same thing ?
"assert debugging purpose , trigger condition should not happen." - : if use exceptions execptions exceptions never thrown
from understanding exceptions can asserts except cannot disabled. disabling asserts reason why should used ?
is there reason why use them rather when use them ?
thanks
i see 2 use cases assertions in production code:
at beginning of method normaly check if given parameter valid. public methods use if statments , exceptions. private methods make simelar checks using assert. idea avoid redundant checks in produktion while in testing (or when somesting goes wrong) can activate assertions double checking.
the other reason use assertions document assumptions used in following code. value considered never null here.
here example code
public class exampel { public publicmethod(final integer i) { if (i == null) { throw new runtimeexception("i should not null"); } privatemethod(i): } private privatemethod(final integer i) { assert != null; // } }
you not want check null several times. assume privatemethod
is used correctly. give reads code hint passing null privatemethod
is wrong thing do.
Comments
Post a Comment