How to use Try and catch with PHP?

Asked

Viewed 1,138 times

1

I have a question about how to apply the try and catch in 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();
     }
    }

The method call is made 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);    
 }

It is correct how the try and catch?

2 answers

5


In this case there is no reason to do so. It is using exception for flow control, and in the worst possible way. If an exception will be captured in the function itself that is thrown is wrong in 100% of the cases. The exception is a way to divert the execution of the code away from where it is.

If the exception is caught outside it is usually wrong in most cases that people do. If used right has very little try-catch in the code. AND almost never capture the Exception.

This case would be simpler that way:

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 in the Github for future reference.

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

Behold Why should we avoid returning error codes?.

Also:

0

The code that is inside Try is the one that will process the data and when something goes wrong it enters Catch. By taking a quick peek at your code I believe you’re applying it correctly. A hint seeks to know the lists of Exception instead of using a generic (Exception).

Browser other questions tagged

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