Forum Moderators: coopster
i'm using the most basic script:
try {
$dbh = new PDO('mysql:host=localhost;dbname=db', 'user', 'password');
echo "<p>Connection SUCCESS!</p>";
// disconnect
$dbh = null;
}
catch (PDOException $e) {
die($e->getMessage());
}
if i run this script with the correct username and password then naturally the success message is displayed, thus i assume pdo is installed properly.
however if i enter an incorrect username, password or database name then i was expecting to get the 'catch' error message written to the page.
but, i'm getting this message:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[28000] [1045] ....etc,etc.
which means to me that the exception is not being caught.
as this script is about as simple as it gets, i'm wondering if i'm missing the point - surely if i enter an incorrect username it should throw an exception and the script should catch it!
any ideas?
i cut and pasted the getMessage example which is as simple as it gets.
and it fails, the error i get is the same-
Fatal Error:uncaught exception ...
if i try the getMessage example with the following code pasted above it:
/*** a default Exception handler ***/
function my_default_handler($exception){
echo "Uncaught exception: " , $exception->getMessage();
}
set_exception_handler('my_default_handler');
then the default handler catches it and the followign message is printed to the page:
Uncaught exception: Some error message
which is correct, in that the default exception handler is obviously catching the exception.
.....
just to be clear, the exact code i initially used is..
<?php
try {
throw new Exception("Some error message");
} catch(Exception $e) {
echo $e->getMessage();
}
?>
and it throws up the: Fatal error, uncaught exception message.
i'm testing this in a file in the root, there is no .htaccess or anything that i imagine could be interfering with the code.
seems very strange to me!
When an exception is thrown, code following the statement will not be executed, and PHP will attempt to find the first matching catch block. 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() [php.net].My emphasis added
Resource: Exceptions [php.net]
I have run into existing exception handler overrides before. I use the set_exception_handler() function to override temporarily with my own and then reset it after I am completed with my portion of the processing. The function will return ... well, here ... read it right from the manual pages ...
Return ValuesReturns the name of the previously defined exception handler, or NULL on error. If no previous handler was defined, NULL is also returned.