0
whereas the "users" table does not exist, catch
be 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();
}
But if an exception is not cast, why the function defined in
set_exception_handler
is called?– Woss
Why an error occurs in the execution of the script (the call of a function that does not exist), although this error is not interpreted as an instance of the Exception class. There was actually an exception in the execution of the code, but it is not the type that the Try/catch loop expects.
– Juven_v
But mistakes are not treated by
set_exception_handler
rather than byset_error_handler
. I tested the question code here and the exception was captured as expected. If the databaseteste
does not exist, the PDO constructor will make an exception. It can better explain the part where you claim that it is not launched?– Woss
In the answer I referred to the second Try/catch (which was the question’s doubt, when the table users did not exist). The first Try/catch actually executes the catch (because the Pdo class throws an Exception of the Pdoexception type, which at some point extends the Exception class). In the second Try/catch, when the query fails, the $resul variable will receive the false value, then when you try to access the fetch function from the $resul variable, an error occurs (which is an Exception relative to what should happen). For the catch nothing happened.
– Juven_v
Wow, I could swear the problem was the first one. I had read that the database didn’t exist. Now it all makes sense. In that case I think it would be best to use a
if
verifying the return of query. Maybe you can add your answer.– Woss