下面来介绍一下关于php中异常处理的方法介绍,有需要学习的异常处理的朋友可参考本教程.
以下是引用片段:
1.允许一个方法给出一个出错标记给客户代码
2.提供程序错误的详细信息
3.让你同时判断多个出错条件,将你的错误报告和程序处理流程分开.
4.返回值必须是独立的类型,不会与正常返回的类型相混淆
两个实例掌握PHP异常处理
例【1】用 try...catch
实例代码如下:
-
- $dsn = 'mysql:host=localhost;dbname=testdb';
- $user = 'dbuser';
- $password = 'dbpass';
- try {
- $dbh = new PDO($dsn, $user, $password);
- echo '如果上面出现异常就不能显示我了';
- } catch (PDOException $e) {
- echo 'Connection failed: ' . $e->__toString();
- }
- ?>
实例代码如下:
- <?php
-
- try {
- $error = '我抛出异常信息,并且跳出try块';
- if(is_dir('./tests')){
- echo 'do sth.';
- }else{
- throw new Exception($error,12345);
- }
- echo '上面有异常的话就轮不到我了!~<br />',"n";
- } catch (Exception $e) {
- echo '捕获异常: ', $e->getMessage(),$e->getCode(), "n<br />";
- }
- echo '继续执行';
- ?>
上面一个朋友说的,下面我自己来写了点程序练习一下:
实例代码如下:
- $a = 20;
-
- try
- {
- if($a == 1)
- {
- throw new Exception("I am 1", 1);
- }
- elseif ($a == 2)
- {
- throw new Exception("I am 2", 3);
- }
- elseif ($a == 3)
- {
- throw new Exception("I am 3", 3);
- }
- elseif ($a == 4)
- {
- throw new Exception("I am 4", 4);
- }
- else
- {
- throw new Exception("Who am I ?", 0);
- }
- }
- catch (Exception $e)
- {
- if($e->getCode() == 1)
- {
- echo "1 : ".$e;
- }
- elseif ($e->getCode() == 2)
- {
- echo "2 : ".$e;
- }
- elseif ($e->getCode() == 3)
- {
- echo "3 : ".$e;
- }
- elseif ($e->getCode() == 4)
- {
- echo "4 : ".$e;
- }
- else
- {
- echo "0 : ".$e;
- }
- }
- echo "
-
- --------------------------------------------------------------------------------
- ";
-
- class A extends Exception{};
- class B extends Exception{};
- try
- {
- if($a == 1)
- {
- throw new A("I am A", 1);
- }
- elseif ($a == 2)
- {
- throw new B("I am B", 2);
- }
- else
- {
- throw new Exception("Who am I ?", 0);
- }
- }
- catch (A $e)
- {
- echo "1 : ".$e;
- }
- catch (B $e)
- {
- echo "2 : ".$e;
- }
- catch (Exception $e)
- {
- echo "0 : ".$e;
- }
- ?>
输出如下:
以下是引用片段:
0 : exception 'Exception' with message 'Who am I ?' in |
D:WebPHPWWWnewtest.php:24 Stack trace: #0 {main}
----------------------------------------------------------------------------
0 : exception 'Exception' with message 'Who am I ?' in D:WebPHPWWWnewtest.php:69 Stack trace: #0 {main}