Exception Launching

0

Since the "users" table does not exist, I would like to understand why instead of catch is executed, the "errors" function is executed

Code:

<?php

$usuario = 'root';

$senha ='';

function errors($e)
{
    echo "Erro dados";
}

set_exception_handler('errors');

try
{

    $conn1 = new PDO('mysql:host=localhost;dbname=teste',$usuario, $senha);

}

catch(Exception $e){

    echo 'Erro ao conectar com o banco';

    die();  
}

try
{

    $sql= "SELECT * FROM usuarios";

    $resul = $conn1->query($sql);

    $resul = $resul->fetch(PDO::FETCH_ASSOC);

    foreach ($resul as $key => $value) {
        echo $key .": ". $value. "</br>";   
    }
}catch(Exception $e)
{

echo "Erro ao selecionar dados";

    die();

}
    
asked by anonymous 20.05.2017 / 20:18

1 answer

2

Basically, an exception is not being thrown. When your query is executed, it does not return a ResultSet, which makes it impossible to call the fetch function. With this, PHP throws an error type called E_NOTICE, which is not an instance of the Exception class.

Anyway the only way (more or less) to make the catch execute is to throw an exception manually inside the try. Something like this:

throw new Exception("Erro na consulta sql");

Example for the second try / catch to work:

try
{
    $sql= "SELECT * FROM usuarios";
    $resul = $conn1->query($sql);

    //quando a query sql falhar, por qualquer motivo, 
    //será retornado o boolean false.
    if($resul === false){
        throw new Exception("Erro na consulta sql, algum campo não existe");    
    }
    $resul = $resul->fetch(PDO::FETCH_ASSOC);

    foreach ($resul as $key => $value) {
    echo $key .": ". $value. "</br>";   
    }
}catch(Exception $e)
{

    echo "Erro ao selecionar dados: " . $e->getMessage();
        die();

}

In this case your set_exception_handler will no longer be executed in this specific situation.

    
20.05.2017 / 23:35