catch

创建于 2024-12-03 / 29
字体: [默认] [大] [更大]

❮ PHP 关键字

实例

捕获异常:

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

定义和用法

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


相关页面

throw关键字。

try关键字。

finally关键字。

在我们的 PHP 异常教程中了解有关 try..catch.finally(异常)的更多信息。


更多实例

实例

对多种异常使用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";
}
?> 亲自试一试 »
❮ PHP 关键字
0 人点赞过