I think the interviewer was trying to figure out if you understand the purpose of runtime exceptions that should signal programmer errors (as opposed to application exceptions that signal runtime problems).
You can and should subclass RuntimeException when your method needs to signal a state that is a programming error, and you need to provide additional information about the error described in the description.
For example, consider a class that allows you to store data in a sparse multidimensional array. One of the APIs that is likely to provide such a class is getter, which accepts an array of indices. The number of indices must be equal to the number of dimensions in the array, and each index must be within its boundaries. Delivering an array parameter that has the wrong number of elements or has one or more elements outside its boundaries is a programming error. You should signal this with a runtime exception. If you want to report this error and provide complete information about what went wrong, your subclass of IllegalArgumentException , a subclass of RuntimeException , to throw your own exception.
Finally, there is another situation where you want to subclass RuntimeException : when you must provide a “regular” exception, but you do not want your users to wrap every call to your API with try / catch . In situations like this, you can replace one method.
void performOperation() throws CustomApplicationException;
using a couple of methods
boolean canPerformOperation(); void performOperation();
The first method tells the caller that it is safe to call the second method in its current state; it never throws an exception.
The second method fails only in the state where the first method returns false , which makes the failure a programming error, thereby justifying the use of a RuntimeException to signal such failures.
source share