PHP Try Catch in Exception Handling -
I have database class dbconnect.php, and processform.php. Inside the dbconnect.php is a way to connect to the database.
If there is an error, how can I throw an exception? Where do I put cache blocks in processform.php? People say that I should not resonate an error directly from inside the class. Here's an example:
& lt ;? Php // dbconnect.php class DbConnect {public function open_connection} / / should I do this? * / $ This- & gt; Conn = PDO ($ dsn, $ this- & gt; username, $ this- & gt; password); If (! $ This-> conn) {new exception throw ('Error connecting to database.'); } / * Or such like * / try {$ this-> conn = PDO ($ dsn, $ this- & gt; username, $ this-> password); } Hold (PDOException $ e) {echo 'error:', $ e-> GetMessage (), '& lt; Br> & # 39; & # 39; }}? & Gt; // processform.php & lt ;? Php require_once 'dbconnect.php'; $ Pdo = New DBCnet ($ host, $ username, $ password); {$ Pdo-> Open_connection (); } Hold (PDOException $ e) {Echo 'Error connecting to database.'); }? & Gt; I really want to try in my code to learn the correct way of applying hold.
You do not have to manually throw an exception, especially on the successful connect: -) < P> Instead you need to tell the PDO that it needs to leave some exceptions when something goes wrong when you open your database connection:
$ options = Array (PDO :: ATTR_ERRMODE = & gt; PDO :: ERRMODE_EXCEPTION); $ This- & gt; Conn = new PDF ($ dsn, $ this-> username, $ this-> password, $ option); Now you can put everything in the try / hold block but it is not necessary; If you do not do this, then php will show you unhandled exceptions with a stack trace when you do not manually capture them. And when you decide that you want to fix - Arrange your visitors to deal with your error, you can set up using your own exception handler. In this way you can handle everything at a place instead of wrapping different sections in the try / hold block, should you like it.
Comments
Post a Comment