PHP Try Catch in Exception Handling -
i have database class dbconnect.php, , processform.php. within dbconnect.php there method connecting database.
if there's error, how throw exception? set seek grab block, in processform.php? people shouldn't echo error straight within class. here's example:
<?php // dbconnect.php class dbconnect { public function open_connection() { /* should this? */ $this->conn = pdo($dsn, $this->username, $this->password); if (!$this->conn) { throw new exception('error connecting database.'); } /* or */ seek { $this->conn = pdo($dsn, $this->username, $this->password); } grab (pdoexception $e) { echo 'error: ', $e->getmessage(), '<br>'; } } ?> // processform.php <?php require_once 'dbconnect.php'; $pdo = new dbconnect($host, $username, $password); seek { $pdo->open_connection(); } grab (pdoexception $e) { echo 'error connecting database.'); } ?>
i want larn right way of implementing seek grab in code.
you don't have throw exception manually, on successful connect :-)
instead need tell pdo needs throw exceptions when goes wrong , can when open database connection:
$options = array(pdo::attr_errmode => pdo::errmode_exception); $this->conn = new pdo($dsn, $this->username, $this->password, $options);
now can set in try
/ catch
blocks not necessary; if don't that, php show unhandled exceptions
finish stack trace when don't grab them manually.
and when decide want fine-tune error handling visitors, can set own exception handler using set_exception_handler()
. way can handle @ 1 place instead of wrapping different sections in try
/ catch
blocks. should prefer of course.
php exception-handling
No comments:
Post a Comment