Uncaught exception 'Exception' PHP

1

Colleagues. I set the code. The solution was based on colleagues putting the throw new Exception () inside the try / catch block and also placed outside the if () conditional. See:

function cadastro($valor){
      $sql = mysqli_query($conexao, "SELECT * FROM tabela WHERE campo = '".$valor."'");

        if(strlen($valor) < 3){
        $erro = "O sabor não pode ser inferior a 3";
        }else{
        $sqlCadastrar = mysqli_query($conexao,"INSERT INTO tabela VALUES(null,'".$valor."');");            

        }
 try{
      if($erro == true){
    throw new Exception($erro);      
    }else if(mysqli_affected_rows($conexao) > 0){
               return "<script>window.location.href='cadastrar.php';</script>"; 
               }
             } catch (Exception $erro) {
                 return $erro->getMessage();
        }  
}
    
asked by anonymous 04.02.2016 / 16:21

1 answer

2

This message is displayed on the screen because your exception was not handled, so a fatal error will be triggered to warn you as explained in the documentation.

  

If an exception is not caught, a PHP Fatal Error will be issued with an "Uncaught Exception ..." message, unless a handler has been defined with set_exception_handler ().

This (strange) example code simulates the problem, catch expects a DogeScareException for a Exception that is different from the expected type for the treatment that was thrown and was not captured.

try{
    throw new Exception("WoOoOoW Exception", 2015);
}catch(DogeScareException $e){
     echo 'Caught exception#';
}   

Another reason is the Marco Aurélio Deleu comment , the throw new Exception(...) must be inside a block try-catch of the contario the exception will never be treated and will literally explode on the screen.

    
04.02.2016 / 18:14