区分 PHP 中的异常和错误
以下讨论错误和异常之间的差异。
- 无法从错误中恢复。错误的唯一解决方案是终止执行。而我们能够通过使用 try-catch 代码块或者向调用方返回异常来从异常中恢复。
- 无法通过 try-catch 代码块来处理错误。即使你使用 try-catch 代码块处理错误,它们在发生时,你的应用也不会恢复。另一方面,异常可以通过 try-catch 代码块来处理,并能够在异常发生时让程序正常运行。
- 异常与应用有关,而错误则与应用运行时所在的与环境有关。
示例
<?php try { $row->insert(); $inserted = true; } catch (Exception $e) { echo "There was an error inserting the row - ".$e->getMessage(); $inserted = false; } echo "Some more stuff"; ?>
解释
程序执行将继续 - 因为你“捕获”了异常。除非捕获异常,否则异常将被视为一个错误。它将允许你在异常失败后继续执行程序。
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
示例
<?php $foo = [bar]; echo $foo; ?>
解释
程序执行将停止并提示 PHP 注意:数组到字符串的转换。
广告