Home > Enterprise >  Please what does (PDOException $e) and PDOException($e->getMessage(), (int)$e->getCode()) mean
Please what does (PDOException $e) and PDOException($e->getMessage(), (int)$e->getCode()) mean

Time:03-28

Can you please explain what (PDOException $e) and PDOException($e->getMessage(), (int)$e->getCode()) does and mean here?

try
  {
    $pdo = new PDO($attr, $user, $pass, $opts);
  }
  catch (PDOException $e)
  {
    throw new PDOException($e->getMessage(), (int)$e->getCode());
  }

CodePudding user response:

Let's compare the output of this code with and without try catch

$pdo = new PDO('foo', 'username', 'password');

will give us

PHP Fatal error: Uncaught PDOException: PDO::__construct():
Argument #1 ($dsn) must be a valid data source name in pdo.php:6
Stack trace:
#0 C:\SERVER\www\htdocs\pdo.php(6): PDO->__construct('foo', 'username', 'password')
#1 {main} thrown in pdo.php on line 6

notice the username and password can be seen in the error message

Now with try catch and re-throw

try
{
    $pdo = new PDO('foo', 'username', 'password');
}
catch (PDOException $e)
{
    throw new PDOException($e->getMessage(), (int)$e->getCode());
}

the output will be

PHP Fatal error:  Uncaught PDOException: PDO::__construct(): 
Argument #1 ($dsn) must be a valid data source name in pdo.php:12
Stack trace:
#0 {main}
  thrown in pdo.php on line 12

as you can see, there is no username or password.

This is the only reason such a clumsy code is employed

  • Related