PHP catch 关键词

定义和用法

catch 关键字用于处理在前面的 try 块中由代码抛出的异常。

相关页面

参考手册:throw 关键字

参考手册:try 关键字

参考手册:finally 关键字

教程:PHP 异常

实例

例子 1

捕获异常:

<?php
try {
  throw new Exception("This is an exception");
} catch(Exception $e) {
  echo $e->getMessage();
}
?>

亲自试一试

例子 2

使用 catch 处理多种类型的异常:

<?php
try {
  $rand = rand(0, 2);
  switch($rand) {
    case 0: throw new Exception();
    case 1: throw new OutOfBoundsException();
    case 2: throw new LogicException();
}

} catch(OutOfBoundsException $e) {
  echo "Caught an out of bounds exception";
} catch(LogicException $e) {
  echo "Caught a logic exception";
} catch(Exception $e) {
  echo "Caught an ordinary exception";
}
?>

亲自试一试