PHP exception handling: how to catch and handle runtime errors?

PHPz
Release: 2024-06-04 12:11:57
Original
1018 people have browsed it

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.

PHP exception handling: how to catch and handle runtime errors?

#PHP Exception Handling: A Guide to Catching and Handling Runtime Errors

What are exceptions?

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.

How to catch exceptions?

Exceptions can be caught using the try...catch statement:

try {
    // 代码块可能会引发异常
} catch (Exception $e) {
    // 当发生异常时执行的代码
}
Copy after login

Any code executed within the try block may throw an exception, and will be handled in the catch block.

How to handle exceptions?

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(); // 打印异常发生的文件路径
}
Copy after login

Practical case

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();
    }
}
Copy after login

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();
    }
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template