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 privatemethodis used correctly. give reads code hint passing null privatemethodis wrong thing do.


Comments

Popular posts from this blog

plot - Remove Objects from Legend When You Have Also Used Fit, Matlab -

java - Why does my date parsing return a weird date? -

Need help in packaging app using TideSDK on Windows -