《PHP和MySQL WEB开发》笔记第七章

来源:互联网 发布:php b2c商城系统二次开 编辑:程序博客网 时间:2024/05/02 04:53
<?/*unit7错误和异常处理*///貌似一个异常会有三个关键字try.throw。catch$a=array();try{throw new Exception('抛出一个异常:');}catch(Exception $e){echo "Exception".$e->getCode().":".$e->getMessage()."<br />in".$e->getFile()."online".$e->getline()."<br />";}//Exception这应该是一个类/*Exception类*/  //exception claa is 内置类  //exceprion 类中的内置方法  /* getcode();返回传递给构造函数的代码 getmessage();返回传递给构造函数的消息 getfile();返回产生错误的代码的完整路径 getline(); gettrace();返回一个包含了异常代码的回退路径的数组 gettraceasstring();上面的这个的字符串形式 _tostring(); */  //Lets try   try{      throw new Exception("我是错误消息");      }  catch(exception $e){      echo $e->getCode();//0      echo $e->getmessage();//我是错误消息      echo $e->getfile();      echo $e->getline();//16      echo $e->getTrace();//array      echo $e->getTraceAsString();          }    //稍微看了一下exception 的构造,知道了大多数的公有方法都是有final前缀的    //用户自定义自己的exception 类的方法如下  class luexception extends Exception{      function __tostring(){          return "<table><tr><td><strong>".$this->getMessage()."</strong></td></tr><tr><td bgcolor=\"red\">".$this->getFile()."的".$this->getLine()."</td></tr></table>";          }      }    try{      throw new luexception("错误消息");      }catch(exception $ee){          echo $ee;          }    /*7.4Bob的汽车零部件商店应用程序的异常*/  //一般错误都出现在文件的i/o中。  /*bob商店的异常处理类*/  class fileopenexception extends Exception{      function __tostring(){          return "fileopenexception!".$this->getCode()." ".$this->getFile()." ".$this->getLine();          }      }  $b="ww";            //在代码的末尾判断异常  try{      if(!isset($b)){          throw new fileopenexception("B is not set.");          }      }  catch(fileopenexception $e){      echo "B is wrong.<br />";      echo $e;      }  catch(exception $ex){      echo $ex;      }     @$a=$b+1;  ?>