php 也有本身的异常处理方法,虽然比不上Java的强大,可是简单的仍是很容易处理的。
<?php try{ $a = 2; echo $a; if($a > 200) { throw new Exception ('更新管理平台密码失败!'); } echo 'ok'; } catch(Exception $e) { echo $e->getMessage(); }
在数据库中使用事物时,用该方法很是方便:php
$state = 0; // 添加事物处理 try { // 开启事物 $GLOBALS['db']->beginTransaction(); // 更新管理平台密码 $state = $GLOBALS['db']->query("update admin_user set password='$password_confirm' where user_id=$user_id"); if($state != true) { throw new Exception ('更新管理平台密码失败!'); } $ret = $this->modify_ldap_pwd($user_name, $user_password_old, $user_password_confirm); if(!$ret) { throw new Exception ('更新LDAP密码失败!'); } // 提交事物 $GLOBALS['db']->commit(); $state = 1; } catch (Exception $e) { // 回滚 $GLOBALS['db']->rollBack(); }
函数封装处理:数据库
define('runcode', 1); function testE($num){ if($num == 1){ return 'hello'; }else{ throw new Exception ( "error"); } } try{ $ret = testE(1); dump($ret); dump(100); } catch (Exception $e ){ echo $e->getMessage(); dump('抛出了异常'); }