Exceptions and state
Lesson 25 of 48 in Coddy's PHP for Dart Developers course.
Dart can throw objects and use typed on clauses, catch and finally; PHP throw requires a Throwable. Catch expected failures at a boundary that can handle them. In either language, validate before mutation so rejection leaves state intact rather than masking a partial update.
Throw an exception to signal a failed contract, and catch only the expected categories at a boundary that can handle them. Validate all preconditions before mutation so rejected operations leave state intact. finally runs during normal return and exception propagation. Do not convert every Throwable into success or hide programming errors.
Dart program
void main() {
try {throw StateError("bad");} on StateError {print("caught");}
}
Source output:
caughtPHP program
demo.php
<?php
declare(strict_types=1);
try {throw new RuntimeException("bad");} catch(RuntimeException $e){echo "caught";} finally{echo ":done\n";}
PHP output:
caught:doneChallenge
EasyInput is [balance,amount]. debit mutates the referenced balance only when amount is positive and affordable. Throw InvalidArgumentException for nonpositive amounts, DomainException for insufficient funds. Driver catches either and prints error:balance; success prints ok:balance. Balance starts nonnegative.
The supplied main script reads one JSON value from standard input, checks the named public APIs, and prints the result. Implement the module declarations without printing; do not replace the launcher or read input from a module. Input satisfies the stated types and bounds.
Edit Functions.php. main.php is the locked entry file. Dependencies use require_once __DIR__ with a relative filename.
Try it yourself
<?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";
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in PHP for Dart Developers
1Values and output
Modules and first runFormatting returned textAssignments and variablesDivision and conversionStrings and byte lengthsExplicit Boolean rulesRecap: receipt text4Functions and modules
Functions and return typesDefaults and named callsVariadic argumentsCallbacks and capturesrequire_once and scopeRecap: integer cents2Control flow
Branches and precedenceStrict match expressionsLoops and early exitsKeys and iterationRecap: shipping rules5Errors and boundaries
Exceptions and stateStrict input validationNull is not falsyRecap: validate a batchPractice on your own: Online PHP compiler