While this is prone to a strong sense of personal opinion, I believe best practice is not to use block else
.
The reasons are as follows:
Code Readability
Adding nested blocks, although in this small example does not make a big impact, will only make it difficult to read the code and make it more complex.
In practice, this can lead to situations with multiple levels of validation, as I have 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 that I am exaggerating, I have not once or twice seen methods with validations of 5, 6 or more levels in methods of financial systems with somewhat complex business rules.
No need
A condition that includes an exception throw, or other statement that stops the execution of the method does not need this type of build. Unnecessary code is 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;
}