예외와 상태
Coddy의 C 개발자를 위한 PHP 코스 레슨. 48개 중 25번째.
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]입니다. debit은 amount가 양수이고 잔액이 충분한 경우에만 참조된 balance를 변경합니다. 0 이하의 amount에는 InvalidArgumentException을, 잔액이 부족한 경우에는 DomainException을 발생시킵니다. 드라이버는 두 예외 중 하나를 잡아 error:balance를 출력하고, 성공하면 ok:balance를 출력합니다. 잔액은 0 이상에서 시작합니다.
제공된 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";
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
C 개발자를 위한 PHP의 모든 레슨
직접 연습해 보세요: 온라인 PHP 컴파일러