Menu
CoddyTech

异常与状态

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

C++ 会抛出异常,并在栈展开期间使用 RAII 析构函数进行清理,而不是使用 finally 关键字。PHP 提供了 catch 和 finally。在这两种语言中,都要在修改状态前进行验证,这样被拒绝的操作就能保持不变量完整,而无需修复部分状态。

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

C++ 程序

#include <iostream>
#include <stdexcept>

int main() {
    int value=4;try{if(value>0)throw std::invalid_argument("bad");value=9;}catch(const std::invalid_argument&){std::cout<<"caught:"<<value<<"\n";}
}

源程序输出:

caught:4

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 才会修改被引用的 balance。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自我测试

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

面向 C++ 开发者的 PHP中的所有课

自己练习: PHP 在线编译器