Sollevare e gestire le eccezioni in PHP

Sollevare e gestire le eccezioni in PHP

In PHP è semplice sollevare e gestire le eccezioni.

L'eccezione viene prima sollevata con throw e quindi intercettata in un blocco try/catch:


function divide($a = 1, $b = 1) {
    if($a === 0 || $b === 0) {
        throw new Exception('Division by zero.');
        return -1;
    }
    return ($a / $b);
}

try {
    $result = divide(4, 0);
} catch(Exception $ex) {
    echo $ex->getMessage(); // 'Division by zero.'
}

Torna su