ZetCode

PHP 异常

最后修改于 2025 年 3 月 11 日

在本文中,我们将展示如何在 PHP 中使用 异常。异常是 PHP 中用于错误处理的机制,它允许开发人员优雅地处理错误并保持对程序流程的控制。异常使用 throw 关键字抛出,并使用 try-catch 块捕获。

PHP 异常的主要特性

异常是 Exception 类或其子类的实例。它们使用 throw 关键字抛出,并使用 try-catch 块捕获。

异常的基本用法

以下示例演示了如何在 PHP 中抛出和捕获异常。

main.php
<?php

declare(strict_types=1);

function divide(int $a, int $b): int
{
    if ($b === 0) {
        throw new Exception("Division by zero is not allowed.");
    }
    return $a / $b;
}

try {
    echo divide(10, 0);
} catch (Exception $e) {
    echo "Caught exception: " . $e->getMessage();
}

在此程序中,如果第二个参数为零,则 divide 函数抛出一个异常。异常在 try-catch 块中被捕获,并显示错误消息。

$ php main.php
Caught exception: Division by zero is not allowed.

自定义异常

以下示例演示了如何在 PHP 中创建和使用自定义异常类。

main.php
<?php

declare(strict_types=1);

class DivisionByZeroException extends Exception
{
    public function __construct()
    {
        parent::__construct("Division by zero is not allowed.");
    }
}

function divide(int $a, int $b): int
{
    if ($b === 0) {
        throw new DivisionByZeroException();
    }
    return $a / $b;
}

try {
    echo divide(10, 0);
} catch (DivisionByZeroException $e) {
    echo "Caught custom exception: " . $e->getMessage();
}

在此程序中,DivisionByZeroException 类扩展了 Exception 类。如果第二个参数为零,则 divide 函数抛出此自定义异常。异常在 try-catch 块中被捕获和处理。

$ php main.php
Caught custom exception: Division by zero is not allowed.

多个 Catch 块

以下示例演示了如何使用多个 catch 块来处理不同类型的异常。

main.php
<?php

declare(strict_types=1);

class DivisionByZeroException extends Exception {}
class InvalidArgumentException extends Exception {}

function divide(int $a, int $b): int
{
    if ($b === 0) {
        throw new DivisionByZeroException("Division by zero is not allowed.");
    }
    if ($a < 0 || $b < 0) {
        throw new InvalidArgumentException("Arguments must be positive.");
    }
    return $a / $b;
}

try {
    echo divide(-10, 5);
} catch (DivisionByZeroException $e) {
    echo "Caught DivisionByZeroException: " . $e->getMessage();
} catch (InvalidArgumentException $e) {
    echo "Caught InvalidArgumentException: " . $e->getMessage();
}

在此程序中,divide 函数根据输入值抛出不同的异常。这些异常在单独的 catch 块中被捕获和处理。

$ php main.php
Caught InvalidArgumentException: Arguments must be positive.

Finally 块

以下示例演示了如何使用 finally 块来执行代码,无论是否抛出异常。

main.php
<?php

declare(strict_types=1);

function divide(int $a, int $b): int
{
    if ($b === 0) {
        throw new Exception("Division by zero is not allowed.");
    }
    return $a / $b;
}

try {
    echo divide(10, 0);
} catch (Exception $e) {
    echo "Caught exception: " . $e->getMessage();
} finally {
    echo "\nFinally block executed.";
}

在此程序中,无论是否抛出异常,finally 块都在 try-catch 块之后执行。

$ php main.php
Caught exception: Division by zero is not allowed.
Finally block executed.

重新抛出异常

以下示例演示了如何在捕获异常后重新抛出异常。

main.php
<?php

declare(strict_types=1);

function divide(int $a, int $b): int
{
    if ($b === 0) {
        throw new Exception("Division by zero is not allowed.");
    }
    return $a / $b;
}

try {
    try {
        echo divide(10, 0);
    } catch (Exception $e) {
        echo "Caught exception: " . $e->getMessage();
        throw $e; // Rethrow the exception
    }
} catch (Exception $e) {
    echo "\nRethrown exception: " . $e->getMessage();
}

在此程序中,异常被捕获、记录,然后重新抛出,以便由外部 catch 块处理。

$ php main.php
Caught exception: Division by zero is not allowed.
Rethrown exception: Division by zero is not allowed.

异常层次结构

以下示例演示了如何根据异常的层次结构捕获异常。

main.php
<?php

declare(strict_types=1);

class CustomException extends Exception {}
class AnotherException extends CustomException {}

function testException()
{
    throw new AnotherException("Another exception occurred.");
}

try {
    testException();
} catch (AnotherException $e) {
    echo "Caught AnotherException: " . $e->getMessage();
} catch (CustomException $e) {
    echo "Caught CustomException: " . $e->getMessage();
} catch (Exception $e) {
    echo "Caught Exception: " . $e->getMessage();
}

在此程序中,AnotherException 首先被捕获,因为它比 CustomExceptionException 更具体。

$ php main.php
Caught AnotherException: Another exception occurred.

来源

PHP 异常 - 文档

在本文中,我们展示了如何在 PHP 中使用 异常 进行错误处理。异常是管理错误和保持对程序流程控制的强大工具。

作者

我叫 Jan Bodnar,是一位对编程充满热情的程序员,拥有丰富的编程经验。自 2007 年以来,我一直在撰写编程文章。迄今为止,我撰写了 1,400 多篇文章和 8 本电子书。我拥有超过十年的编程教学经验。

列出 所有 PHP 教程