php - Using Exceptions to control application flow -
i writing web app in php , have decided use exceptions (duh!).
i not find answer whether putting try , catch blocks in functions considered bad code.
i using exceptions handle database errors (application errors handled via simple function adds them array , displayed user). try blocks placed on functions require database connection.
the code in question is:
public function db_conn_verify() { if(!isset($this->_mysqli)){ throw new exception("network error: database connection not established."); } else { return null; } } and example function using code:
public function get_users() { try { $this->db_conn_verify(); //rest of function code return true; } catch(exception $e) { core::system_error('function get_users()', $e->getmessage()); return false; } } also better extend exception class , use new exception class handle application errors?
thanks
i suggest use this:
public function get_users() { try { if( !isset($this->_mysqli) ) { throw new exception("network error: database connection not established."); } //rest of function code } catch(exception $e) { core::system_error('function get_users()', $e->getmessage()); } } i prefer use exends of exception, same. exdending exception can see php documentation example #5
edit: immediate use of try-catch on database connection error can try this:
try{ $mysqli = new mysqli("localhost", "user", "password", "database"); if ($mysqli->connect_errno) { throw new exception("network error: database connection not established."); } } catch(exception $e) { core::system_error('function get_users()', $e->getmessage()); }
Comments
Post a Comment