I'm having difficulties understanding how to handle unchecked exceptions.
If the method doesn't declare the exception and I am not forced to handle it, how do I even know the method throws an exception?
Unchecked exceptions are for programming errors, as I have read, so to avoid a NullPointerException
, I would introduce a null check. Or for an ArrayIndexOutOfBoundsException
I would check how I access the array.
But when I don't know that a method throws a custom unchecked exception, how am I supposed to handle this?
And how do you propagate exceptions from the data layer to the user interface? Those must be checked exceptions, right?
I would let the data layer throw checked DataLayerExceptions
and then have a try-catch-block in the presenter class (given I am using MVP) and then in the catch-block set the error message on the view...
Or can this be done using unchecked exceptions?
EDIT
Thanks for the replies so far.
Here is a concrete example I am faced with.
I am getting started with Spring and in a book I saw a UserRepository
class that uses a JDBCTemplate
to retrieve data from the database. The UserRepositoty
contains a method somewhat like this:
@Override
public List<User> findAll() {
String sql = "select id, username, email, password from p_user";
return new ArrayList<>(jdbcTemplate.query(sql, rowMapper));
}
Now, the query method of the jdbcTemplate throws a DataAccessException
, which is a runtime exception.
I knwo this, because I looked at the method signature.
Now, how would I handle this exception? Surely, the user needs some type of feedback that something went wrong. And surely, I would log the exception.
But where would I catch this exception?
Should I catch it right there and then rethrow my own unchecked exception?
Or should I declare a throws DataAccessException
on the findAll
method and then deal with the exception in the calling class (which may be a service or presenter of some sort)?
Or should I make sure that the conditions under which the exception is thrown can never occur (in case those are even controllable by me)?