异常与状态
Coddy 面向 C 开发者的 PHP 课程的第 25 课,共 48 课。
C 通常会返回状态,并通过输出指针写入成功结果;它没有内置的异常或 finally 语法。PHP 会抛出和捕获异常,并可以在 finally 中执行清理。在修改状态前先进行验证,以便预期的拒绝操作仍能保持相同的状态不变量。
抛出异常以表示契约失败,并且只在能够处理异常的边界处捕获预期的类别。在修改状态前验证所有前置条件,以便被拒绝的操作不会改变状态。正常返回和异常传播期间都会运行 finally。不要把每个 Throwable 都转换成成功,也不要隐藏编程错误。
C 程序
#include <stdbool.h>
#include <stdio.h>
static bool double_nonnegative(int value, int *result) {
if (value < 0) {
return false;
}
*result = value * 2;
return true;
}
int main(void) {
int result = 0;
if (!double_nonnegative(-1, &result)) {
puts("caught");
} else {
printf("%d\n", result);
}
return 0;
}源程序输出:
caughtPHP 程序
demo.php
<?php
declare(strict_types=1);
try {throw new RuntimeException("bad");} catch(RuntimeException $e){echo "caught";} finally{echo ":done\n";}
PHP 输出:
caught:done挑战
简单输入为 [balance,amount]。只有当 amount 为正数且余额足够时,debit 才会修改被引用的余额。金额不为正数时抛出 InvalidArgumentException,资金不足时抛出 DomainException。驱动程序会捕获这两种异常,并输出 error:balance;成功时输出 ok:balance。余额初始值为非负数。
提供的主脚本会从标准输入读取一个 JSON 值,检查指定的公共 API,并输出结果。实现模块声明,不要打印内容;不要替换启动器,也不要从模块读取输入。输入符合指定的类型和范围限制。
编辑 Functions.php。main.php 是锁定的入口文件。依赖项使用 require_once __DIR__ 和相对文件名。
亲手试试
<?php
declare(strict_types=1);
require_once __DIR__."/Functions.php";
function ensure(bool $ok,string $message):void{if(!$ok)throw new RuntimeException("API: ".$message);}
function debitReport(array $input):string{$balance=$input[0];try{debit($balance,$input[1]);$status="ok";}catch(InvalidArgumentException|DomainException $e){$status="error";}return $status.":".$balance;}
$input=json_decode(trim(stream_get_contents(STDIN)),true,512,JSON_THROW_ON_ERROR);
$b=7;try{debit($b,8);throw new RuntimeException("missing rejection");}catch(DomainException $e){}ensure($b===7,"atomic error");debit($b,2);ensure($b===5,"debit");
echo debitReport($input),"\n";
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 C 开发者的 PHP中的所有课
自己练习: PHP 在线编译器