Skip to content

错误 与 异常

  • 错误: 错误是PHP内部产生的, 通常表示严重的、不可恢复的问题, 比如语法错误、内存溢出等
  • 异常: 由应用程序主动抛出,表示可预见的问题情况
php
<?php
# 语法错误: 最后没有分号, 会导致 php 解释器无法工作, 这就是错误
$name = "hello"
php
<?php
try {
  throw new Exception("error");
}catch(Exception $e){
  echo "<pre>";
  var_dump($e);
  echo "</pre>";
}

捕获异常

php
<?php
try {
  // 可能会出现异常的代码
}catch(Exception $e){
  // 捕获异常
} finally{
  // 不管是否出现异常,都会执行
}

抛出异常

php
<?php

// 使用 throw 关键字
throw new Exception("error message");

自定义异常

php
<?php

// 自定义异常
class CustomExpection extends Expection  {}

// 手动抛出自定义异常
throw new CustomException("error message from CustomException", 1);

Released under the MIT License.