Home > Article > Backend Development > PHP exception handling: how to catch and handle runtime errors?
Exception is an object in PHP that represents a program runtime error. Exceptions can be caught and handled using the try...catch statement: code that may throw an exception is executed within a try block. Use the $e object in the catch block to access the details of the exception, including message, code, and file path.
In PHP, an exception is an object that represents an error or unexpected state during program execution. They are often used to handle unexpected situations, such as a file that does not exist or a failed database connection.
Exceptions can be caught using the try...catch
statement:
try { // 代码块可能会引发异常 } catch (Exception $e) { // 当发生异常时执行的代码 }
Any code executed within the try
block may throw an exception, and will be handled in the catch
block.
In the catch
block, you can access the object $e
that raised the exception. This object provides detailed information about the exception, including error message, code, and file path.
try { // 代码块可能会引发异常 } catch (Exception $e) { echo $e->getMessage(); // 打印错误消息 echo $e->getCode(); // 打印错误代码 echo $e->getFile(); // 打印异常发生的文件路径 }
File reading:
try { // 打开文件 $file = fopen('file.txt', 'r'); // 读取文件内容 $contents = fread($file, filesize('file.txt')); } catch (Exception $e) { if ($e->getCode() === 2) { // 文件不存在 echo '文件不存在。'; } else { echo '发生未知错误:' . $e->getMessage(); } }
Database connection:
try { // 创建数据库连接 $conn = new PDO('mysql:host=localhost;dbname=mydb', 'user', 'password'); } catch (PDOException $e) { if ($e->getCode() === '2002') { // 数据库连接失败 echo '无法连接到数据库。'; } else { echo '发生未知错误:' . $e->getMessage(); } }
The above is the detailed content of PHP exception handling: how to catch and handle runtime errors?. For more information, please follow other related articles on the PHP Chinese website!