I have the following doubt concerning which exception to throw if list is empty
public class XYZ implements Runnable {
private List<File> contractFileList;
@Override
public void run() {
contractFileList = some method that will return the list;
//now i want to check if returned contractFile is empty or not , if yes then raise the exception
if (contractFileList.isEmpty()) {
// throw new ?????
}
}
}
I am runing this code inside a batch, I want to throw some exception that will stop the batch execution.
That looks like
IllegalStateExceptionto me.Basically your object is not in a valid state for
runto be called.I wouldn’t create your own exception for this unless you expect it to be deliberately caught elsewhere. It sounds like this would only occur due to a programming error rather than an unexpected situation… in which case an unchecked exception is appropriate, and
IllegalStateExceptiondescribes the general nature of the problem quite clearly.You can put a detailed cause within the message of the exception (explaining that the “illegal state” was that the list was empty).
I suggest you try to avoid creating a separate exception type for every little thing that can go wrong – unless you’re catching these exceptions separately, having different types doesn’t help; it only adds to the clutter. An exception which is of the right broad type but has a useful message provides just as much benefit without as much cognitive overhead.
Note that you can’t use a checked exception if you’re implementing
Runnable.runanyway, as that isn’t declared to throw any checked exceptions. You’d have to wrap it in an unchecked exception (e.g.RuntimeException) at which point there’s even less benefit.