Menu
CoddyTech

Exceptions and state

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

C# and PHP support typed catches and finally without Java-style checked exceptions. PHP Error and Exception both implement Throwable; C# exception hierarchies use System.Exception. Validate before mutation and catch expected contract failures instead of hiding programming errors.

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.

C# program

#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;

class Program {

 static void Main() {
  try{throw new InvalidOperationException("bad");}catch(InvalidOperationException){Console.Write("caught");}finally{Console.WriteLine(":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 C# Developers

Practice on your own: Online PHP compiler