java – What is the good practice when throwing exception inside if?

Question:

What is the best practice in this case, using the else even knowing that the if will throw an exception or not?

option 1 (with else ):

if (condicao){
  throw new RuntimeException("Mensagem");
}else{
  System.out.println("Não deu exception");
}

option 2 (no else ):

if (condicao){
  throw new RuntimeException("Mensagem");
}
System.out.println("Não deu exception");

Answer:

While this is prone to a strong sense of personal opinion, I believe the best practice is not to use the else block.

The reasons are as follows:

Code readability

Adding nested blocks, although in this small example doesn't make a big impact, it will only make the code harder to read and more complex.

In practice, this can lead to situations with multiple levels of validation, as I've sometimes seen in systems out there:

if (condicao1){
    throw new RuntimeException("Mensagem 1");
}else{
    System.out.println("Não deu exception 1");
    if (condicao1){
        throw new RuntimeException("Mensagem 2");
    }else{
        System.out.println("Ainda não deu exception 2");
        if (condicao1){
            throw new RuntimeException("Mensagem 3");
        }else{
            System.out.println("Ainda não deu exception 3");
        }
    }
}

For those who think I'm exaggerating, not once or twice have I seen methods with validations of 5, 6 or more levels in financial systems methods with somewhat complex business rules.

It is not necessary

A condition that includes an exception throw, or another instruction that interrupts the method's execution does not need this type of construction. Unnecessary code is a waste of time.

It is better to separate the initial validations

The initial validations of a method do not need and probably should not influence the main logic of the method.

public int meuMetodo(String parametro) {

    if (parametro == null || parametro.isEmpty()) 
        throw new IllegalArgumentException("Parâmetro não informado!");

    //lógica aqui
    return 123;

}
Scroll to Top