Menu
CoddyTech

Exceptions and state

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

Java distinguishes checked and unchecked exceptions, requiring catch-or-declare for checked exceptions. PHP has no checked-exception declaration mechanism. Typed catch and finally exist in both; validate before mutation so expected rejection preserves state.

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.

Java program

import java.util.*;

class Main {

  public static void main(String[] args) throws Exception {
    try{throw new IllegalArgumentException("bad");}catch(IllegalArgumentException e){System.out.print("caught");}finally{System.out.println(":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 Java Developers

Practice on your own: Online PHP compiler