Home > php教程 > php手册 > body text

php的异常处理基础方法

WBOY
Release: 2016-06-13 10:15:13
Original
921 people have browsed it

下面来介绍一下关于php中异常处理的方法介绍,有需要学习的异常处理的朋友可参考本教程。

以下是引用片段:

1.允许一个方法给出一个出错标记给客户代码
2.提供程序错误的详细信息
3.让你同时判断多个出错条件,将你的错误报告和程序处理流程分开。
4.返回值必须是独立的类型,不会与正常返回的类型相混淆
 
两个实例掌握PHP异常处理

//例【1】用 try...catch

 代码如下 复制代码
/* PDO连接mysql数据库,如果没看过PDO,先看下PDO的构造函数,要不跳过例1看例2 */
$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();
}
?>

 代码如下 复制代码
//例[2] try..cathc 和 throw一起用
try {
$error = '我抛出异常信息,并且跳出try块';
if(is_dir('./tests')){
echo 'do sth.';
}else{
throw new Exception($error,12345);
}
echo '上面有异常的话就轮不到我了!~
',"n";
} catch (Exception $e) {
echo '捕获异常: ', $e->getMessage(),$e->getCode(), "n
"; //显示$error和123456
}
echo '继续执行';
?>

上面一个朋友说的,下面我自己来写了点程序练习一下:

以下是代码片段:

 代码如下 复制代码


$a = 20;

// 使用常规catch的例子
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} 

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template