Where should I place the Try/Catch blocks using MVC?

Asked

Viewed 645 times

2

I am making a web application in java and I have some doubts regarding the block Try catch, I am using the standard MVC and I have the following codes:

Controller:

try {
    String pesquisa = "%" + request.getParameter("pesquisa") + "%";
    List<Administrador> adm = serviceAdm.listarAdm(pesquisa);

    request.setAttribute("adm", adm);
    RequestDispatcher disp = request.getRequestDispatcher("administradores.jsp");
    disp.forward(request, response);
} catch (Exception ex) {
    System.out.println("Erro: " + ex);
    request.setAttribute("erro", true);
    RequestDispatcher disp = request.getRequestDispatcher("principal.jsp");
    disp.forward(request, response);
}

Model:

public List<Administrador> listarAdm(String pesquisa) {
    try {
        return (List<Administrador>) admDB.selectAdms(pesquisa);
    } catch (Exception ex) {
        return null;
    }
}

And I use the DAO to make the connection:

public List<Administrador> selectAdms(String pesquisa) {
    List<Administrador> usuarios = manager
            .createQuery("select a from Administrador a where nome LIKE :pesquisa")
            .setParameter("pesquisa", pesquisa).getResultList();

    return usuarios;
}

I wonder if in case of any problem in the Model, how I put it to return null, he will not enter the catch of Controller? I must put the try/catch in all files or only in Controllers?

  • 2

    I have two questions to answer your answer : http://answall.com/questions/58536/blocos-try-catch?rq=1 and http://answall.com/questions/108484/uso-espec%C3%Adfico-do-Try-catch? Rq=1

  • Did you create your own MVC? Or is it some specific framework?

2 answers

2


The idea of using Try catch is precisely to capture exceptions that the application can launch and execute an alternative operation. Then you should put scopes of Try catch every time the application might throw an error, ie if an error may occur in a file, use Try catch.

For your code, the controller catch will make an exception because you try to use a variable that is null. Then your logic will work correctly.

  • 5

    Downvoters, could explain to Jader (who is answering for the first time on the site), the reason for the negative vote?

1

You can use throws in the signature of the model methods to echo the exceptions directly to the Controller instead of the Try catch or use the Try catch itself and within the catch you throw new to specify the error generated in the model.

Browser other questions tagged

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