java - Custom RunTime Exceptions -
so regarding interview question asked. interviewer started on asking me how create our custom exceptions. on answering that, asked me how i'd create runtimeexceptions. said we'd create them in same way create checked exceptions. our custom exception extend runtimeexception class. asked in scenarios create own runtimeexception. couldn't think of answer that. in none of projects, created custom runtimeexceptions.
i think should never create runtimeexceptions. jvm can fail in finite number of ways , handles them well. while writing application can't predict runtime exceptions can occur , hence shouldn't need handle them. , if can predict conditions, aren't runtimeexceptions then. since neither need new runtime exceptions, nor need handling of runtimeexceptions, why ever need create custom runtimeexception. can pre-think of possible failure condition should handled @ compile time , checked exception. right? things cannot handled @ compile time , ones depend on run time things go category of runtimeexceptions.
even if write custom runtimeexceptions , custom method should throw runtimeexception - how make sure method throw particular runtimeexception. how mapping. doesn't seem possible me.
am missing something/ many things here? kindly advice.
thanks, chan.
i think interviewer trying see if understand purpose of runtime exceptions, signal programmer's errors (as opposed application exceptions, signal problems execution environment).
you can , should create subclasses of runtimeexception
whenever method needs signal condition amounts programming error, , need provide additional information regarding error exception describes.
for example, consider class lets store data in sparse multidimensional array. 1 of apis such class provide getter takes array of indexes. number of indexes needs equal number of dimensions in array, , each index must within bounds. supplying array parameter has incorrect number of elements, or has 1 or more element outside bounds, programming error. need signal runtime exception. if want signal error, , provide full account of went wrong, subclass illegalargumentexception
, subclass of runtimeexception
, build own exception.
finally, there 1 more situation when want subclass runtimeexception
: when should provide "regular" exception, not want users wrap each call of api in try
/catch
block. in situations these, can replace single method
void performoperation() throws customapplicationexception;
with pair of methods
boolean canperformoperation(); void performoperation();
the first method tells caller safe call second method in current state; never throws exception.
the second method fail in state when first method returns false
, making failure programming error, justifying use of runtimeexception
signal such failures.
Comments
Post a Comment