Menu
CoddyTech

Exceptions and state

Lesson 25 of 48 in Coddy's PHP for JavaScript Developers course.

JavaScript permits throwing arbitrary values and has an untyped catch binding. PHP throws objects implementing Throwable and can select typed catch clauses. Do not catch all failures as business errors; distinguish expected rejection from programming mistakes and preserve state before throwing.

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.

JavaScript program

try {throw new Error("bad");} catch(e) {process.stdout.write("caught");} finally {console.log(":done");}

Source output:

caught:done

PHP 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:done
challenge icon

Challenge

Easy

Input 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";
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in PHP for JavaScript Developers

Practice on your own: Online PHP compiler