异常与状态
Coddy 面向 Kotlin 开发者的 PHP 课程的第 25 课,共 48 课。
Kotlin 异常不需要检查,可以使用类型化的 catch 和 finally 处理。PHP 同样不要求声明检查型异常。在边界处捕获预期的契约失败,并在修改状态前进行验证,不要把每个编程错误都转换成看似成功的结果。
抛出异常以表示契约失败,并且只在能够处理异常的边界处捕获预期类别的异常。在修改状态前验证所有前置条件,这样被拒绝的操作就会保持状态不变。正常返回和异常传播时都会运行 finally。不要把每个 Throwable 都转换成成功,也不要掩盖编程错误。
Kotlin 程序
fun main(){
try {error("bad")} catch(e:IllegalStateException){println("caught")}
}
源代码输出:
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 才会修改引用的余额。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";
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Kotlin 开发者的 PHP中的所有课
自己练习: PHP 在线编译器