Return from catch clean code

1

I'm reading the Clean Code book from the Robert C. Martin series. And a very common situation was presented in my daily life.

    public static void main(String[] args) {
    String nome = null;

    try {
        if (nome.length() > 10) {
            System.out.println("Nome maior que 10 caracteres");
        } else {
            System.out.println("Nome menor que 10 caracteres");
        }
    } catch (Exception e) {
        // Não encontro o registro no banco de dados
    }

}

Sometimes we perform some operation that the exception is unavoidable. In this code for example, when the exception happens in nome.length() I want the error to be ignored.

I leave the comment to describe the reason for the error? Are you shooting the comment? Or can we work as another approach?

Remembering that I do not want to raise an exception!

    
asked by anonymous 12.09.2017 / 14:34

1 answer

6

A practical example of how to eliminate an exception handler, which simplifies code and gives you more performance:

public static void main(String[] args) {
    String nome = null; //obviamente que é só para ilustrar, ninguém faria isto, certo?
    System.out.println(nome != null && nome.length() > 10 ? "Nome maior que 10 caracteres" : "Nome menor que 10 caracteres");
}

You may wonder about the handling of the database error. It did not make any sense. If I had something that could cause such an error it would be the case to catch this exception , not the Exception . Just deal with the exceptions you have to deal with. That is, do not deal with other, general exceptions, and do not capture exceptions that can be avoided in the code. What can be avoided and is not can be considered programming error and try-catch is not suitable for this, correct the error in your code.

Read more about the links featured in the comments above.

    
12.09.2017 / 14:59