NullPointerException occurring

2

My teacher uses EasyAccept technology as error validation. One of the tests requires the use of Exception . In the code below, I was able to handle in a way that I think is appropriate, but it persists in one and the same error.

package maisPop;

import java.util.List;

import easyaccept.EasyAccept;
import usuariosExceptions.EntradaException;

public class Facade {

    private List<Usuario> usuarios;

    public static void main(String[] args) {
        args = new String[] {
                "maisPop.Facade",
                "resources/Scripts de Teste/usecase_1.txt"};
        EasyAccept.main(args);
    }

    public void iniciaSistema() {
        //iniciar sistema
    }

    public void cadastraUsuario(String nome, String email, String senha, String dataNasc, String imagem) throws Exception{
        Usuario novoUsuario = new Usuario(nome, email, senha, dataNasc, imagem);
        if (getUsuarios().contains(novoUsuario))
            throw new EntradaException("Usuario ja esta cadastrado no +Pop.");
        usuarios.add(novoUsuario);
    }

    public void cadastraUsuario(String nome, String email, String senha, String dataNasc) throws Exception{
        Usuario novoUsuario = new Usuario(nome, email, senha, dataNasc, "resources/default.png");
        if (getUsuarios().contains(novoUsuario))
            throw new EntradaException("Usuario ja esta cadastrado no +Pop.");
        usuarios.add(novoUsuario);
    }

    public List<Usuario> getUsuarios() {
        return usuarios;
    }
}

Next to another class that will perform user registration.

package maisPop;

import java.text.ParseException;
import java.util.Date;

import usuariosExceptions.AtualizaPerfilException;

public class Usuario {

    private String email, senha, nome;
    private Date dataNasc;
    private String imagem;

    public Usuario(String email, String senha, String nome, String dataNasc, String imagem) throws Exception {
        setEmail(email);
        setSenha(senha);
        setNome(nome);
        this.dataNasc = UtilUsuario.formataData(dataNasc);
    }

    public String getEmail() {
        return email;
    }

    public void setEmail (String email) throws AtualizaPerfilException {
        if (email.equals("") || email == null){
            throw new AtualizaPerfilException("Email nao pode ser nulo ou vazio.");
        }else if (UtilUsuario.validaEmail(email) == false){
            throw new AtualizaPerfilException("Erro na atualizacao de perfil. Formato de e-mail esta invalido.");
        }
        this.email = email;
    }

    public String getSenha() {
        return senha;
    }
    public void setSenha(String senha) {
        this.senha = senha;
    }
    public String getNome() {
        return nome;
    }
    public void setNome(String nome) throws AtualizaPerfilException {
        if (nome == null || nome.equals(""))
            throw new AtualizaPerfilException(
                    "Erro na atualizacao de perfil. Nome dx usuarix nao pode ser vazio.");
        this.nome = nome;
    }

    public Date getDataNasc() {
        return dataNasc;
    }

    public void setDataNasc(String novaDataNasc) throws AtualizaPerfilException, ParseException{
        if (UtilUsuario.validaDiaDaData(novaDataNasc) == true
                || UtilUsuario.validaIntervalosDeData(novaDataNasc) == false)
            throw new AtualizaPerfilException(
                    "Erro na atualizacao de perfil. Formato de data esta invalida.");
        if (UtilUsuario.isDateValid(novaDataNasc) == false)
            throw new AtualizaPerfilException(
                    "Erro na atualizacao de perfil. Data nao existe.");
        this.dataNasc = UtilUsuario.formataData(novaDataNasc);
    }

    public String getImagem() {
        return imagem;
    }
    public void setImagem(String imagem) throws AtualizaPerfilException {
        if (nome == null || nome.equals(""))
            throw new AtualizaPerfilException("Imagem nao pode ser nula ou vazia.");
        this.imagem = imagem;
    }
}

And also this class UtilUsuario that performs the validations for the Exception :

package maisPop;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import usuariosExceptions.ErroCadastroException;

public class UtilUsuario {

    public UtilUsuario() {

    }

    ArrayList<String> listaDePossiveisEmails = new ArrayList<String>();

    public static void validaDataCompleta(String dataNasc) throws ErroCadastroException {
        if (dataNasc == null || dataNasc.equals("")
                || validaIntervalosDeData(dataNasc) == false)
            throw new ErroCadastroException(
                    "Erro no cadastro de Usuarios. Data nao existe.");
    }

    public static void validaDia(String dataNasc) throws ErroCadastroException {
        if (validaDiaDaData(dataNasc) == true)
            throw new ErroCadastroException(
                    "Erro no cadastro de Usuarios. Formato de data esta invalida.");
    }

    public static void validaSenha(String senha) throws ErroCadastroException {
        if (senha == null || senha.equals("") || senha.length() < 3)
            throw new ErroCadastroException(
                    "A senha nao pode ser nula, vazia ou menor que 3 caracteres.");
    }

    public static void validaEmailUsuario(String email) throws ErroCadastroException {
        if (email == null || email.equals("") || validaEmail(email) == false)
            throw new ErroCadastroException(
                    "Erro no cadastro de Usuarios. Formato de e-mail esta invalido.");
    }

    public static void validaNome(String nome) throws ErroCadastroException {
        if (nome == null || nome.equals("") || nome.trim().equals(""))
            throw new ErroCadastroException(
                    "Erro no cadastro de Usuarios. Nome dx usuarix nao pode ser vazio.");
    }

    public static boolean validaIntervalosDeData(String data) {
        String[] valores = data.split("/");

        if (!data.matches("([0-9]{2})/([0-9]{2})/([0-9]{4})")
                || Integer.parseInt(valores[0]) < 1
                || Integer.parseInt(valores[0]) > 31)
            return false;
        if (!data.matches("([0-9]{2})/([0-9]{2})/([0-9]{4})")
                || Integer.parseInt(valores[1]) < 1
                || Integer.parseInt(valores[1]) > 12)
            return false;
        if (!data.matches("([0-9]{2})/([0-9]{2})/([0-9]{4})")
                || Integer.parseInt(valores[2]) < 1)
            return false;
        return true;
    }

    public static boolean validaDiaDaData(String data) {
        String[] dia = data.split("/");
        if (dia[0].length() > 2)
            return true;
        return false;
    }

    public static boolean validaEmail(String email) {
        return true;
    }

    public static Date formataData(String data) throws ParseException {
        if (data == null || data.equals(""))
            return null;

        Date date = null;
        try {
            DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
            date = (java.util.Date) formatter.parse(data);
        } catch (ParseException e) {
            throw e;
        }
        return date;
    }

    public static boolean isDateValid(String strDate) {
        DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
        formatter.setLenient(false);
        try {
            Date date = formatter.parse(strDate);
            return true;
        } catch (ParseException e) {
            return false;
        }
    }

All Exceptions are correct, the message it returns is:

   At line 15: Expected <Erro no cadastro de Usuarios. Nome dx usuarix nao pode ser vazio.>, but no error occurred.
   At line 16: Expected <Erro no cadastro de Usuarios. Nome dx usuarix nao pode ser vazio.>, but no error occurred.
   At line 17: Expected <Erro no cadastro de Usuarios. Formato de e-mail esta invalido.>, but no error occurred.
   At line 18: Expected <Erro no cadastro de Usuarios. Formato de data esta invalida.>, but no error occurred.
   At line 19: Expected <Erro no cadastro de Usuarios. Data nao existe.>, but no error occurred.

But all these errors are already treated as you can see above. But the problem insists on continuing.

Below are the .txt lines for the above errors:

15. expectError "Erro no cadastro de Usuarios. Nome dx usuarix nao pode ser vazio." cadastraUsuario nome="" email="[email protected]" senha="senha_besta" dataNasc="10/10/2010"
16. expectError "Erro no cadastro de Usuarios. Nome dx usuarix nao pode ser vazio."  cadastraUsuario nome="  " email="[email protected]" senha="senha_besta" dataNasc="10/10/2010"
17. expectError "Erro no cadastro de Usuarios. Formato de e-mail esta invalido."  cadastraUsuario nome="Fulaninho" email="alguem@email" senha="senha_besta" dataNasc="10/10/2010"
18. expectError "Erro no cadastro de Usuarios. Formato de data esta invalida."  cadastraUsuario nome="Fulaninho" email="[email protected]" senha="senha_besta" dataNasc="1510/10/2010"
19. expectError "Erro no cadastro de Usuarios. Data nao existe."  cadastraUsuario nome="Fulaninho" email="[email protected]" senha="senha_besta" dataNasc="32/10/2010"
    
asked by anonymous 15.10.2015 / 21:19

1 answer

5

Error NullPointerException should not be handled, it should be resolved, after all it is a programming error. In fact most of the exceptions should not be addressed.

Within setEmail() there is a line:

if (email.equals("") || email == null){

Change it to:

if (email == null || email.equals("")) {

In the original when email is null it generates this exception trying to access equals("") , after all it can not access any method in something that is null . In other places it seems to be all right, compare in the right order.

The comparison of null before is just to not let it try to make an illegal operation, since the relational operators are short-circuit , that is, they only evaluate the other operand when it still can not guarantee what the outcome will be. In case if the first operand is true , you do not have to execute the second operand, after all a true for all || valer true .

I do not know if you have other problems. The question is not very informative. You may have other places that you need to protect against null and have not been done. The expression dia[0].length() potentially could give another type of error and was not handled or resolved.

But if there are any exceptions that should be addressed in the code, I can not help much because the code does not address any of them. Exception throwing is not the same as exception handling. Quite the contrary.

There are several things that could have been done better. But the biggest one is that exceptions should not be used to validate data . Not everyone agrees to this, in Java the culture is doing it, but it is a abuse of the resource, it is spurious . You have better ways of doing this.

If an expression can result in true ou false 'never compare it to those values. Simplify (the bottom line is simplified):

if (validaDiaDaData(dataNasc) == true)
if (validaDiaDaData(dataNasc)) //melhor assim

if (dataNasc == null || dataNasc.equals("")
        || !validaIntervalosDeData(dataNasc))

The same goes for anything that expects a Boolean value:

String[] dia = data.split("/");
if (dia[0].length() > 2)
    return true;
return false;

It looks better this way:

String[] dia = data.split("/");
return dia[0].length() > 2;

Making a try-catch to give throw e; is a waste and causes loss of information about the exception. If you do not know how to resolve the exception, do not capture it.

Capturing an exception to return true or false is not at all bad, but you have to know well why you're doing it. There can be a solution by accident. I say it's not all bad because you're just trading an exception for a normal value to handle validation. This is the bandstand. You are correcting an error that the Java API committed. In this case it looks like it did right .

Additional important reading .

    
15.10.2015 / 21:57