Nullpointerexception occurring

Asked

Viewed 144 times

2

My teacher uses the technology of EasyAccept as validation of errors. In one of the tests it is necessary to use Exception. In the code below, I managed to treat in a way that I THINK is appropriate, but it persists in the same mistake.

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 validating the treatment of 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.

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

Below are the lines of . txt referring to 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"
  • 2

    I didn’t quite understand what the problem is. You say that errors are dealt with. Where? I didn’t see any treatment for them. There are several errors in the code that are independent of what you are talking about and should, or at least could be improved. One of them will generate a NullPointerException. Is that the problem? There are some conceptual problems, but the main one I doubt your teacher considers a mistake. I don’t like the idea of a course using such libraries.

  • Oh young man, that’s the problem. When I deal with Exception for it to always return true regardless of the validation, it from the Nullpointerexception error, could you explain to me how to treat this Nullpointerexception problem? Which command line is it on? Thanks in advance!

  • You can simplify Date date = null;&#xA; try {&#xA; DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");&#xA; date = (java.util.Date) formatter.parse(data);&#xA; } catch (ParseException e) {&#xA; throw e;&#xA; }&#xA; return date; so as to remain return new SimpleDateFormat("dd/MM/yyyy").parse(data);.

1 answer

6


Error of NullPointerException should not be dealt with, it should be solved, after all it is a programming error. In fact most of the exceptions should not be dealt with.

Within the setEmail() there’s a line:

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

Change her to:

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

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

The comparison of null before it is precisely to not let him try to make an illegal operation, since relational operators are short-Circuit, that is, they only evaluate the other operand when it cannot yet guarantee what the result will be. In the case if the first operand holds true, there is no need to execute the second operand, after all just a true for the whole of || be worth true.

I don’t know if you have other problems. The question is not very informative. You may have other places you need to protect against null and has not been done. The expression dia[0].length() can potentially give another type of error and has not been treated or resolved.

But if there are any exceptions that should be dealt with in the code, I can’t help much because the code doesn’t deal with any of them. Casting exception is not the same as treating exception. Quite the contrary.

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

If an expression can result in true or false never compare it to these 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;

Looks better this way:

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

I put in the Github for future reference.

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

Capture an exception to return true or false it is not at all evil, but it has to know well why it is doing. It cannot be a solution by accident. I say that it is not at all bad because you are exchanging an exception for a normal value to treat validation. This is the correct way. You are correcting an error that the Java API made. In this case it seems you’ve done well.

Important additional reading.

Browser other questions tagged

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