java - How does one decide to create a checked excpetion or an unchecked exception -


this question has answer here:

i want know how 1 know create , throw checked exception or unchecked exception.

for example have service takes data , validates before using it. during validation field did not meet rules , want throw exception validationexception(). how know of decide should checked or unchecked.

in case calling external web service code example google stock api. let's assume have timeout of 3 seconds. if time exprires want throw exception backendexception(). how know if should checked exception or unchecked exception.

thanks in advance.

there might different opinions i'd difference how caller should handle exception:

  • if want make sure caller handles exception either doing (logging, trying recover etc.) or rethrowing use checked exception. example said validationexception: if data invalid caller should have handle that, e.g. telling fix data or trying else.
  • it don't want force caller handle exceptions should not thrown (e.g. programming errors etc.) use unchecked exception. example might dreaded nullpointerexception: should not happen want use null might considered programming error. if null should not might want use checked exception instead.

    note libraries/methods use illegalargumentexception unchecked exception. if exception thrown there's programming error in contract of method (e.g. parameter value must not negative) violated , caller should fix code or checks himself.

another point of view might be: exception expected thrown in cases or not? expected exceptions (that still mean kind of error happened) checked exceptions since way you'd communicate caller should expect exceptions being thrown in cases (e.g. if data invalid). if exception unexpected should not force caller handle such exception since you'd not expect thrown @ - unchecked exception.


Comments

Popular posts from this blog

unity3d - Rotate an object to face an opposite direction -

angular - Is it possible to get native element for formControl? -

javascript - Why jQuery Select box change event is now working? -