My common opinion is that you will never catch an exception that you do not know how to handle . In particular, in this case, since IndexOutOfBoundsException is a RuntimeException and therefore does not need to be caught, you can just let it distribute the call stack. The caller requests the object by the list index, so it seems to have some idea of ​​which index to request - then throwing or allowing the throwing of the thrown IndexOutOfBoundsException seems completely natural.
The only other obvious option would be to catch the exception and return null , but I really don't like this approach for such egregious errors on the part of the caller when there is no reasonable return value. You can also return a special instance of User (see the Zero Object Template), but even this does not relieve the caller of the responsibility for checking what has been returned. Depending on the interface and implementation of User such checks may be trivial or not, but they still need to be done.
If you want to clearly indicate that a method can throw an exception, just say this:
public User getUser(int index) throws IndexOutOfBoundsException { ... }
Or, like @ Bela Vizer , suppose you wrap it in an IllegalArgumentException (which is also a RuntimeException).
And as pointed out by @ lc. it’s best to first check if the object exists before trying to access it. Handle the error you are expecting rather than relying on the get() method to throw an exception. You should still be clearly aware that the method may cause such an exception, however, if, for example, the collection is modified between validation and return. With multi-threaded software on multi-core processors, as you know, unfamiliar things happen.
source share