which exception to throw if list is empty in java?

That looks like IllegalStateException to me.

Signals that a method has been invoked at an illegal or inappropriate time.

Basically your object is not in a valid state for run to 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 IllegalStateException describes 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.run anyway, 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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)