Best practices with Java exception handling

Asked

Viewed 1,030 times

7

How best to work with more than one exception in Java?

In the code below, I see the possibility of giving two errors NullPointer or SQLException. If I put one catch for every exception is the best way?

public Boolean cadastro(Contato contato) throws SQLException, ExceptionCadastro {
    try {
        PreparedStatement p = (PreparedStatement) conexao.prepareStatement("insert into contatos (nome, email, telefone, endereco) values (?,?,?,?)");
        p.setString(1, contato.getNome());
        p.setString(2, contato.getEmail());
        p.setString(3, contato.getTelefone());
        p.setString(4, contato.getEndereco());
        p.executeUpdate();
        p.close();
    } catch (NullPointerException e) {
        e.printStackTrace();
    } finally{
        conexao.close();
    }
    return true;
}
  • 5

    nullpointer must be detected and fixed, not captured. I’ve never seen case where capture is the best option. If there is risk of null data, a conditional validation should be made, not capture nullpointer.

  • 5

    Regarding connection exceptions, I strongly recommend reading:How Try-with-Resources works?

  • Okay Diego, I agree with you, I just used nullpointer as an example.

  • 4

    Does this code compile? It should not because there is a situation that it does not return anything, I don’t know if Java assumes any pattern. Otherwise that’s what @diegofm said. But if it were two mistakes that should be captured, it depends on whether you want to do the same thing or different things, and you should only capture what will do something useful. Almost always print the stacktrace or something like it is not something useful, this treatment should occur in the main() or something like that. Most of the catches that programmers make should not be made.

  • See more on http://answall.com/questions/tagged/exce%C3%A7%C3%a3o? Sort=votes&pageSize=50

  • 2

    @bigown The code doesn’t have much quality, but compiles yes. It always returns true if an exception has not been cast (which means that the return is not for much in this case). It is interesting to note that it returns true even if a NullPointerException within the try!

  • Yes Victor, I fixed it hehe. Thanks for the personal help.

Show 2 more comments

1 answer

10


As already stated in the comments, programming errors like the NullPointerException should never be captured, they should be fixed. Ideally it should only occur during your testing in development. So the best thing to do is to break the application so you can fix the problem.

Just capture exceptions so you can do something useful and recover from that mistake. Programming errors or even environmental errors (caused by JVM directly or indirectly) have no treatment. Even one ArithmeticException is a programming error, you should not let a calculation give an error.

Then we entered into a certain controversy. Java culture indicates that in most cases where an operation can give a problem it must generate an exception and it must be treated to recover (this has changed since Java 8, some programmers have not noticed this).

In other cultures it is more common to follow the path of trying to avoid error before it happens or check the error in another way (Java itself opts for this at several points) other than the exception.

In cases where you can check the error otherwise or you can avoid it I always prefer this way, most Java programmers still prefer to let the exception occur, even being a slower option. There are situations that only the exception is adequate. But this is changing and programmers have adopted other techniques more and more.

In cases where you should even capture the exception, only do so where you can solve something. Even if this something is only show a message to the user or log in the error somewhere. If you can’t solve the problem or do something useful to capture the exception?

Almost always print the stack trace or doing something equivalent means that the application has given up and will break, or at least return to its beginning. Why go around capturing an exception in all the code to do the same thing? Let the exception bubble to the call stack and only treat at a neutral location.

My applications usually have much less catchis that most Java applications out there, in some cases the difference reaches thousands.

And if you have a throw within a catch it’s almost always a mistake.

If you really need to treat more than one exception in that same location have two strategies:

  • The action to be taken is the same, make a catch with the OR operator to accept any of them:

    try { 
        ...
    } catch (ExceptionCadastro | SQLException ex) { 
        ...
    }
    
  • If you need each error to have a different action use more than one catch:

    try { 
        ...
    } catch (ExceptionCadastro) { 
        ...
    } catch (SQLException ex) { 
        ...
    }
    

I put in the Github for future reference.

And will not capture Exception unless you know what you’re doing.

Can read more about it on the site. I highly recommend, most programmers do not understand and abuse exceptions.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.