我有以下代码,我想知道我是否可以使用try&catch如下:
class fun_database implements idbInfo{ private $srvr=idbInfo::srvr_name; private $usr=idbInfo::usrnm; private $pass=idbInfo::psswrd; private $db=idbInfo::db_name; public function connct(){ $hookup = new mysqli($this->srvr, $this->usr, $this->pass, $this->db); if ($hookup->connect_errno) { throw new Exception("Error Processing Request", 1); } } public function sql_require_all($table_name, $table_col){ $hookup = new connct(); $result = $hookup->query("SELECT $table_col FROM $table_name"); if($hookup->error()){ throw new Exception("Error Processing Request", 1); } return $result->num_rows; } }
这是一个与mysql的简单连接,并在那里执行一些查询.这是以上函数的实际调用:
$conn = new fun_database(); try{ $result = $conn->sql_require_all('wordtypes', 'types'); } catch(Exception $err){ echo "Problems at:". $err->getMessage(); } return "";
我要问的是一点理论.很可能这段代码不工作(我还没有测试).我只是想知道是否可以通过"尝试"'捕获'两个异常(因为你可以看到第一个'throw'在fun_database的第二个方法中,第二个'throw'在第一个方法中同样的对象,只从第二种方法调用).
抱歉让它变得太复杂但仍然无法弄清楚这个try/catch的结构是否有效.
你只能捕捉不同类型的例外......
class fun_database implements idbInfo{ private $srvr=idbInfo::srvr_name; private $usr=idbInfo::usrnm; private $pass=idbInfo::psswrd; private $db=idbInfo::db_name; public function connct(){ $hookup = new mysqli($this->srvr, $this->usr, $this->pass, $this->db); if ($hookup->connect_errno) { throw new DomainException("Error Processing Request", 1); } } public function sql_require_all($table_name, $table_col){ $hookup = new connct(); $result = $hookup->query("SELECT $table_col FROM $table_name"); if($hookup->error()){ throw new Exception("Error Processing Request", 1); } return $result->num_rows; } }
然后:
try{ $conn = new fun_database(); $result = $conn->sql_require_all('wordtypes', 'types'); } catch(DomainException $err){ echo "This Problem at:". $err->getMessage(); } catch(Exception $err){ echo "That Problem at:". $err->getMessage(); } return "";
虽然我相信,你需要在try块中进行类实例化.