Errors in PHP

Error hierarchy


Throwing an error


function summation(...$numbers) {
  return array_reduce($numbers, function($sum, $number) {
    if (is_numeric($number)) {
      return $sum + $number;
    } else {
      throw new Exception("Not as Number");
    }
  });
}

var_dump(summation(1, 2, 3)); //=> int(6)
var_dump(summation(1, 2, "a")); //=> Fatal error: Uncaught Exception: Not as Number

Handling errors


function summation(...$numbers) {
  return array_reduce($numbers, function($sum, $number) {
    if (is_numeric($number)) {
      return $sum + $number;
    } else {
      throw new Exception("Not as Number");
    }
  });
}

try {
  var_dump(summation(1, 2, 3)); //=> int(6)
} catch (Exception $e) {
  echo 'Caught exception: ',  $e->getMessage(), "\n";
} finally {
  echo 'Finally'; //=> Finally
}

try {
  var_dump(summation(1, 2, 3)); //=> int(6)
  var_dump(summation(1, 2, "a"));
} catch (Exception $e) {
  echo 'Caught exception: ',  $e->getMessage(), "\n"; //=> Fatal error: Uncaught Exception: Not as Number
} finally {
  echo 'Finally'; //=> Finally
}

Custom Error Types


class NaNException extends Exception {
  public function __construct()
  {
    parent::__construct('Not as Number', 0, null);
  }
}

function summation(...$numbers) {
  return array_reduce($numbers, function($sum, $number) {
    if (is_numeric($number)) {
      return $sum + $number;
    } else {
      throw new NaNException();
    }
  });
}

try {
  var_dump(summation(1, 2, 3)); //=> int(6)
  var_dump(summation(1, 2, "a"));
} catch (Exception $e) {
  echo 'Caught exception: ',  $e->getMessage(), "\n"; //=> Fatal error: Uncaught Exception: Not as Number
} finally {
  echo 'Finally'; //=> Finally
}

References