与以前的版本相比,如何处理PHP 7中的异常? 核心机构仍然是
块。 多个try...catch
块可用于处理不同的异常类型。 最后,无论是抛出还是被捕获,可选的try
块执行。catch
>catch
这是一个基本示例。 finally
块捕获此异常,显示错误消息,而
catch-all。
try { // Code that might throw an exception $file = fopen("nonexistent.txt", "r"); if ($file === false) { throw new Exception("Could not open file."); } fclose($file); } catch (Exception $e) { // Handle the exception echo "An error occurred: " . $e->getMessage(); } finally { // Code that always executes echo "\nThis always runs."; }
catch (Exception $e)
finally
>清理>中的资源:finally
使用try
> block以在Exception
>如何在PHP 7中创建自定义异常,以进行更好的错误管理?
try { // Code that might throw an exception $file = fopen("nonexistent.txt", "r"); if ($file === false) { throw new Exception("Could not open file."); } fclose($file); } catch (Exception $e) { // Handle the exception echo "An error occurred: " . $e->getMessage(); } finally { // Code that always executes echo "\nThis always runs."; }
MyCustomException
data
>来创建自定义,此示例定义了
> php 7和更早版本之间的异常处理的差异有何不同?
PHP 7给异常提供了一些改进:PHP 7中的set_exception_handler()
No more reliance for all exceptions:set_exception_handler()
While 以上是如何处理PHP 7中的例外?的详细内容。更多信息请关注PHP中文网其他相关文章!