How to use try and catch with PHP?

1

I have a question about how to apply try and catch to a method.

public function cadastrarUsuarios(parametros){

 mysqli_query($this->conexao,"INSERT....");

// Aqui que vem a dúvida

    try{
        if(mysqli_affected_rows($this->conexao) > 0){
           $_SESSION["Sucesso"] = time() + 3;
           return "<script>window.location.href='pagina.php';</script>";
        }else{
           $_SESSION["Erro"] = time() + 3;
           $erro = '';
          throw new Exception($erro);
        }
      }catch (Exception $erro){
            return $erro->getMessage();
     }
    }

Calling the method is done on another page and at the top:

 include("classes/metodosClass.php");
 $metodos = new metodosClass();

 if(filter_input(INPUT_POST, "Submit") == "Cadastrar"){    
   ....    
  echo $metodos->cadastrarUsuarios(parametros);    
 }

Is the correct way to try and catch be applied?

    
asked by anonymous 28.12.2017 / 11:57

2 answers

5

In this case there is no reason to do this. You are using exception for flow control , and in the worst possible way. If an exception is caught in the function itself that is thrown it is wrong in 100% of cases. The exception is a way to deflect code execution far from where it is.

If the exception is caught outside it is often wrong in most cases that people do. If used right, it has very little try-catch in code. And almost never captures Exception .

This case would be simpler like this:

public function cadastrarUsuarios(parametros) {
    mysqli_query($this->conexao,"INSERT....");
    if (mysqli_affected_rows($this->conexao) > 0) {
        $_SESSION["Sucesso"] = time() + 3;
        return "<script>window.location.href='pagina.php';</script>";
    } else {
        $_SESSION["Erro"] = time() + 3;
        return NULL;
    }
}

$resultado = $metodos->cadastrarUsuarios(parametros);
if (is_null($resultado)) echo "deu erro";
else echo $resultado;

I put it in GitHub for future reference.

In case PHP could not use NULL , it could be a Boolean. Actually anything that is not expected, I could even use the empty string if it is guaranteed that in normal condition would never have a result like this, but I have doubts if this can be guaranteed in this case. p>

See Why should we avoid returning error codes? .

Also:

28.12.2017 / 12:18
0

The code inside the Try is the one that will do the processing of the data and when something goes wrong it goes inside the Catch. Giving a quick pass in your code I believe you are applying correctly. A tip looks for the exception lists instead of using a generic one (Exception).

    
28.12.2017 / 12:04