蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行 PHP 8.4 try/catch/finally、自定义异常、重抛与顶层处理器实验

PHPWindows x64、PHP 8.4 本地 CLI 环境。explore-exception.php
explore-exception.php175 行
<?php
declare(strict_types=1);

class CustomEmailException extends Exception
{
    public function errorMessage(): string
    {
        return '错误行号 ' . $this->getLine() . ' in ' . basename($this->getFile())
            . ': ' . $this->getMessage() . ' 不是一个合法的 E-Mail 地址';
    }
}

function checkNum(int $number): bool
{
    if ($number > 1) {
        throw new Exception('变量值必须小于等于 1');
    }
    return true;
}

$cases = [];

// Case 1: Basic try / throw / catch / finally control flow
$okReachedAfter = false;
$okFinally = false;
try {
    $okResult = checkNum(1);
    $okReachedAfter = true;
} finally {
    $okFinally = true;
}

$errReachedAfter = false;
$errMessage = '';
$errFinally = false;
try {
    checkNum(2);
    $errReachedAfter = true;
} catch (Exception $e) {
    $errMessage = 'Message: ' . $e->getMessage();
} finally {
    $errFinally = true;
}

$actual1 = [
    'ok_result' => $okResult,
    'ok_reached_after' => $okReachedAfter,
    'ok_finally' => $okFinally,
    'err_reached_after' => $errReachedAfter,
    'err_message' => $errMessage,
    'err_finally' => $errFinally,
];
$expected1 = [
    'ok_result' => true,
    'ok_reached_after' => true,
    'ok_finally' => true,
    'err_reached_after' => false,
    'err_message' => 'Message: 变量值必须小于等于 1',
    'err_finally' => true,
];
$cases[] = [
    'name' => 'try_throw_catch_finally',
    'passed' => $actual1 === $expected1,
    'expected' => $expected1,
    'actual' => $actual1,
];

// Case 2: Custom Exception subclass inheriting getLine()/getFile()/getMessage()
$badEmail = 'someone@example...com';
$customMsg = '';
$customLine = 0;
try {
    if (filter_var($badEmail, FILTER_VALIDATE_EMAIL) === false) {
        throw new CustomEmailException($badEmail);
    }
} catch (CustomEmailException $e) {
    $customMsg = $e->errorMessage();
    $customLine = $e->getLine();
}

$actual2 = [
    'caught_custom' => $customMsg !== '',
    'line_positive' => $customLine > 0,
    'contains_file' => str_contains($customMsg, 'explore-exception.php'),
    'contains_email' => str_contains($customMsg, 'someone@example...com 不是一个合法的 E-Mail 地址'),
];
$expected2 = [
    'caught_custom' => true,
    'line_positive' => true,
    'contains_file' => true,
    'contains_email' => true,
];
$cases[] = [
    'name' => 'custom_exception_subclass',
    'passed' => $actual2 === $expected2,
    'expected' => $expected2,
    'actual' => $actual2,
];

// Case 3: Multiple catch blocks & rethrowing Exception as user-friendly CustomEmailException
$email = 'someone@example.com';
$multiCatchBranch = '';
try {
    if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
        throw new CustomEmailException($email);
    }
    if (str_contains($email, 'example')) {
        throw new Exception("$email 是 example 邮箱");
    }
} catch (CustomEmailException $e) {
    $multiCatchBranch = 'custom:' . $e->errorMessage();
} catch (Exception $e) {
    $multiCatchBranch = 'base:' . $e->getMessage();
}

$rethrowResult = '';
try {
    try {
        if (str_contains($email, 'example')) {
            throw new Exception($email);
        }
    } catch (Exception $e) {
        throw new CustomEmailException($e->getMessage(), 0, $e);
    }
} catch (CustomEmailException $e) {
    $rethrowResult = $e->getMessage() . ' 不是一个合法的 E-Mail 地址。';
    $hasPrevious = $e->getPrevious() instanceof Exception;
}

$actual3 = [
    'multi_catch_branch' => $multiCatchBranch,
    'rethrow_result' => $rethrowResult,
    'preserves_previous' => $hasPrevious,
];
$expected3 = [
    'multi_catch_branch' => 'base:someone@example.com 是 example 邮箱',
    'rethrow_result' => 'someone@example.com 不是一个合法的 E-Mail 地址。',
    'preserves_previous' => true,
];
$cases[] = [
    'name' => 'multiple_catch_and_rethrow',
    'passed' => $actual3 === $expected3,
    'expected' => $expected3,
    'actual' => $actual3,
];

// Case 4: set_exception_handler() registration and handler formatting
$handler = static function (Throwable $exception): string {
    return 'Exception: ' . $exception->getMessage();
};
$prevBefore = set_exception_handler($handler);
$prevOnReset = set_exception_handler(null);
restore_exception_handler();
restore_exception_handler();

$formatted = $handler(new Exception('Uncaught Exception occurred'));
$actual4 = [
    'prev_initially_null' => $prevBefore === null,
    'registered_callable_returned' => $prevOnReset === $handler,
    'handler_output' => $formatted,
];
$expected4 = [
    'prev_initially_null' => true,
    'registered_callable_returned' => true,
    'handler_output' => 'Exception: Uncaught Exception occurred',
];
$cases[] = [
    'name' => 'top_level_exception_handler_registration',
    'passed' => $actual4 === $expected4,
    'expected' => $expected4,
    'actual' => $actual4,
];

echo json_encode(['version' => PHP_VERSION, 'cases' => $cases], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n";
本例需在 Windows x64、PHP 8.4 本地 CLI 环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、PHP 8.4 本地 CLI 环境。

入口文件:projects/php-exception-lab/explore-exception.php

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-exception.php,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、PHP 8.4 本地 CLI 环境。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:PHP

课程关联工程包(登记关联95章) · 含当前章节或实例 · mbskycom202612a1232.zip

下载课程关联工程包:PHP

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1242.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习