I'm using the following script to use a database using PHP:
Nội dung chính
- Table of Contents
- Global exception handler
- Can we catch fatal error in PHP?
- How can I get 500 error in PHP?
- What does fatal error mean in PHP?
- How do I fix uncaught error in PHP?
try{
$db = new PDO['mysql:host='.$host.';port='.$port.';dbname='.$db, $user, $pass, $options];
}
catch[Exception $e]{
$GLOBALS['errors'][] = $e;
}
Now, I want to use this database handle to do a request using this code:
try{
$query = $db->prepare["INSERT INTO users [...] VALUES [...];"];
$query->execute[array[
'...' => $...,
'...' => $...
]];
}
catch[Exception $e]{
$GLOBALS['errors'][] = $e;
}
Here is the problem:
- When the connection to the DB is OK, everything works,
- When the connection fails but I don't use the DB, I have the
$GLOBALS['errors'][]
array and the script is still running afterwards, - When the connection to the DB has failed, I get the following fatal error:
Notice: Undefined variable: db in C:\xampp\htdocs[...]\test.php on line 32
Fatal error: Call to a member function prepare[] on a non-object in C:\xampp\htdocs[...]\test.php on line 32
Note: Line 32 is the $query = $db->prepare[...]
instruction.
That is to say, the script crashes, and the try/catch seems to be useless. Do you know why this second try/catch don't works and how to solve it?
Thanks for the help!
EDIT: There are some really good replies. I've validated one which is not exactly what I wanted to do, but which is probably the best approach.
demis dot palma at tiscali dot it ¶
6 years ago
Throwable does not work on PHP 5.x.
To catch both exceptions and errors in PHP 5.x and 7, add a catch block for Exception AFTER catching Throwable first.
Once PHP 5.x support is no longer needed, the block catching Exception can be removed.
try
{
// Code that may throw an Exception or Error.
}
catch [Throwable $t]
{
// Executed only in PHP 7, will not match in PHP 5
}
catch [Exception $e]
{
// Executed only in PHP 5, will not be reached in PHP 7
}
lubaev dot ka at gmail dot com ¶
5 years ago
php 7.1
try {
// Code that may throw an Exception or ArithmeticError.
} catch [ArithmeticError | Exception $e] {
// pass
}
diogoca at gmail dot com ¶
2 years ago
Examples
Example #4 Throwing an Exception
The above example will output:
0.2 Caught exception: Division by zero. Hello World
Example #5 Exception handling with a finally
block
The above example will output:
0.2 First finally. Caught exception: Division by zero. Second finally. Hello World
Example #6 Interaction between the finally
block and return
The above example will output:
Example #7 Nested Exception
The above example will output:
Example #8 Multi catch exception handling
The above example will output:
Example #9 Omitting the caught variable
Only permitted in PHP 8.0.0 and later.