Exceptions and state
Lesson 25 of 48 in Coddy's PHP for GDScript Developers course.
GDScript commonly signals expected failures through return statuses or result dictionaries rather than catchable exceptions. PHP offers throw, typed catch and finally. Translate the error contract deliberately, validating before mutation so rejected operations keep the same state invariant.
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.
GDScript program
extends SceneTree
func checked_double(n):
if n < 0:
return {"ok": false}
return {"ok": true, "value": n * 2}
func _init():
var result = checked_double(-2)
if result["ok"]:
print(result["value"])
else:
print("invalid")
quit()Source output:
invalidPHP 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 GDScript 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