Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

Keyword throw

Raise an object implementing Throwable and transfer control to a matching handler or up the call stack.

Version: PHP 8.4; repository runtime, production runtime not attested

Syntax

$item = $map[$key] ?? throw new OutOfBoundsException();

Raise an object implementing Throwable and transfer control to a matching handler or up the call stack. Since PHP 8 throw is an expression, so it can supply the missing branch of the null-coalescing operator. A thrown exception interrupts subsequent evaluation on that path.

function requireKey(array $row){return $row["id"] ?? throw new OutOfBoundsException("missing");}
echo requireKey(["id"=>0])," "; try{requireKey([]);}catch(OutOfBoundsException $e){echo $e->getMessage();}
0 missing

Examples

<?php
function requireKey(array $row){return $row["id"] ?? throw new OutOfBoundsException("missing");}
echo requireKey(["id"=>0])," "; try{requireKey([]);}catch(OutOfBoundsException $e){echo $e->getMessage();}

Result

0 missing

Sources