Menu
CoddyTech

异常与状态

Coddy 面向 Rust 开发者的 PHP 课程的第 25 课,共 48 课。

Rust 通常使用 Result 表示可恢复的失败,并通过 ? 传播错误,而不是使用异常。PHP 会抛出 Throwable 对象,并使用 catch 和 finally 处理它们。应有意转换预期的拒绝情况,并在修改状态前进行验证,这样失败的操作才能保留原有状态。

抛出异常以表示契约失败,并且只在能够处理异常的边界捕获预期类别。修改状态前验证所有前置条件,这样被拒绝的操作就不会改变状态。正常返回和传播异常时,finally 都会运行。不要把每个 Throwable 都转换成成功,也不要隐藏编程错误。

Rust 程序

fn main() {
let result:Result<i32,&str>=Err("bad"); match result {Ok(n)=>println!("{}",n),Err(_)=>println!("caught")};
}

源代码输出:

caught

PHP 程序

demo.php

<?php
declare(strict_types=1);
try {throw new RuntimeException("bad");} catch(RuntimeException $e){echo "caught";} finally{echo ":done\n";}

PHP 输出:

caught:done
challenge icon

挑战

简单

输入为 [balance,amount]。只有当 amount 为正数且余额足够时,debit 才会修改被引用的余额。amount 非正数时抛出 InvalidArgumentException,资金不足时抛出 DomainException。驱动程序会捕获这两种异常,并输出 error:balance;成功时输出 ok:balance。余额初始值非负。

提供的 main 脚本会从标准输入读取一个 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";
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 Rust 开发者的 PHP中的所有课

自己练习: PHP 在线编译器