Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to handle unchecked exceptions?

Tags:

java

exception

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)?

like image 974
user3813234 Avatar asked Apr 19 '17 11:04

user3813234


People also ask

How do you handle unchecked exceptions?

An unchecked exception (also known as an runtime exception) in Java is something that has gone wrong with the program and is unrecoverable. Just because this is not a compile time exception, meaning you do not need to handle it, that does not mean you don't need to be concerned about it.

Can we throws unchecked exception in Java?

Both checked and unchecked exceptions can be thrown using the throw keyword. When an exception is thrown using the throw keyword, the flow of execution of the program is stopped and the control is transferred to the nearest enclosing try-catch block that matches the type of exception thrown.

Do you need to declare unchecked exceptions?

You can but never need to declare unchecked exceptions, whether you declare them yourself or not. Exceptions inheriting from RuntimeException are unchecked. Save this answer.

What happens if a program does not handle an unchecked exception?

If your code does not handle and exception when it is thrown, this prints an error message and crashes the program.


2 Answers

I'm having difficulties understanding how to handle unchecked exceptions.

The how is easy. You handle them just like a checked exception. You use a try / catch. (To catch them all, catch RuntimeException, or catch Exception if you want checked exceptions as well. But beware of catching Error or Throwable, and of catching more exceptions than you expect or you can actually handle..)

What you really are asking is how to know when they will be thrown. That is more difficult.

  • As you observed, some unchecked exceptions are thrown by the language itself. In theory, it is possible to write code so that this won't happen. In practice: 1) people make mistakes, 2) too many defensive checks are onerous ... and pointless.

  • Other unchecked exceptions are explicitly declared as being thrown, or are documented as being thrown in a method or constructor's javadocs. (In fact, I would say that a well designed API should document the unchecked exceptions that it expects to throw or propagate.)

  • In the problem cases, you won't know about it until you see the exception at runtime.

The last case illustrates the need for thorough and repeatable testing as part of your development cycle.


But when I don't know that a method throws a custom unchecked exception, how am I supposed to handle this?

In general, you don't.

Any unexpected exception should be treated as a bug. You find either it in test or in production. You fix it. If you have fixed it properly the unexpected exception doesn't recur ... or it is now expected and your code handles it.

And the corollary is that if you do catch and handle an unexpected exception, it is a really bad idea for your code to pretend that nothing bad has happened. At the very least, the exception needs to be logged so that the programmer has something to work with to find the root cause.


And how do you propagate exceptions from the data layer to the user interface?

Generally, it is a bad idea to show exceptions (especially stacktraces!) to users. Normally, you catch them, log them ... together with the stacktrace ... and then tell the user: "Something bad happened: please report this to XXX with the following extra information".

Those must be checked exceptions, right?

Modulo the above ... No. They don't have to be checked exceptions.


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.

You could do that. Modulo the point about showing exceptions to users.

Clearly, if you are going to take this approach, you need to be able to distinguish between the anticipated exceptions that you can explain to the user, handle and "carry on" versus the unanticipated exceptions that cannot be explained and cannot be recovered from. You may have some scheme in mind for doing that ...


Bottom line, there is no simple formula or "best practice" that will solve this problem for you. It requires thought and design ... and care ... and TESTING.

like image 182
Stephen C Avatar answered Sep 25 '22 03:09

Stephen C


When you write small "learning" applications; then it is absolutely fine to just let unchecked exceptions "bubble up" to the main method; and even have that stack trace printed to you on the command line.

In a "real world" application; you would at some level ensure that something catches such exceptions; to do things like:

  • present a meaningful error message to the user
  • create some sort of log entry for later debugging
  • decide whether the application can continue; or should "crash" (probably something that rarely do in the real world)

In other words: one important non-functional requirement of "real world" applications is robustness. You don't want that a missing null-check somewhere tears down your whole application. Thus you need to make sure that your application can continue to function in such situations. (and please note: I am not saying that such things are easy to implement).

Beyond that: you can use your own checked exception; but the big disadvantage there: they mess up your method signatures. But this is a highly opinionated discussion (and although certain important people claim "the war checked vs. unchecked is over; and unchecked won"); official documentation by Oracle still suggests that checked exceptions have their place in the real world.

like image 23
GhostCat Avatar answered Sep 22 '22 03:09

GhostCat