Eccezioni PHP
Cos'è un'eccezione?
Un'eccezione è un oggetto che descrive un errore o un comportamento imprevisto di uno script PHP.
Le eccezioni vengono generate da molte funzioni e classi PHP.
Anche le funzioni e le classi definite dall'utente possono generare eccezioni.
Le eccezioni sono un buon modo per interrompere una funzione quando incontra dati che non può utilizzare.
Lanciare un'eccezione
L' throw
istruzione consente a una funzione o a un metodo definito dall'utente di generare un'eccezione. Quando viene generata un'eccezione, il codice che la segue non verrà eseguito.
Se un'eccezione non viene rilevata, si verificherà un errore irreversibile con un messaggio "Eccezione non rilevata".
Proviamo a lanciare un'eccezione senza catturarla:
Esempio
<?php
function divide($dividend, $divisor) {
if($divisor == 0)
{
throw new Exception("Division by zero");
}
return $dividend / $divisor;
}
echo divide(5, 0);
?>
Il risultato sarà simile a questo:
Fatal error: Uncaught Exception: Division by zero in
C:\webfolder\test.php:4
Stack trace: #0 C:\webfolder\test.php(9):
divide(5, 0) #1 {main} thrown in C:\webfolder\test.php on line 4
La dichiarazione try... catch
Per evitare l'errore dell'esempio sopra, possiamo usare l'
try...catch
istruzione per catturare le eccezioni e continuare il processo.
Sintassi
try {
code that can throw exceptions
} catch(Exception $e) {
code that runs when an exception is caught
}
Esempio
Mostra un messaggio quando viene generata un'eccezione:
<?php
function divide($dividend, $divisor) {
if($divisor ==
0) {
throw new Exception("Division by zero");
}
return $dividend / $divisor;
}
try {
echo
divide(5, 0);
} catch(Exception $e) {
echo "Unable to divide.";
}
?>
Il blocco catch indica il tipo di eccezione da catturare e il nome della variabile che può essere utilizzata per accedere all'eccezione. Nell'esempio sopra, il tipo di eccezione è Exception
e il nome della variabile è $e
.
La prova... la cattura... finalmente la dichiarazione
L' try...catch...finally
istruzione può essere utilizzata per catturare le eccezioni. Il codice nel
finally
blocco verrà sempre eseguito indipendentemente dal fatto che sia stata rilevata un'eccezione. Se
finally
è presente, il catch
blocco è facoltativo.
Sintassi
try {
code that can throw exceptions
} catch(Exception $e) {
code that runs when an exception is caught
} finally {
code that
always runs regardless of whether an exception was caught
}
Esempio
Mostra un messaggio quando viene generata un'eccezione e quindi indica che il processo è terminato:
<?php
function divide($dividend, $divisor) {
if($divisor
== 0) {
throw new Exception("Division by zero");
}
return $dividend / $divisor;
}
try {
echo
divide(5, 0);
} catch(Exception $e) {
echo "Unable to
divide. ";
} finally {
echo "Process complete.";
}
?>
Esempio
Genera una stringa anche se non è stata rilevata un'eccezione:
<?php
function divide($dividend, $divisor) {
if($divisor == 0)
{
throw new Exception("Division by zero");
}
return $dividend / $divisor;
}
try {
echo divide(5, 0);
} finally {
echo
"Process complete.";
}
?>
L'oggetto d'eccezione
L'oggetto Exception contiene informazioni sull'errore o sul comportamento imprevisto riscontrato dalla funzione.
Sintassi
new Exception(message, code, previous)
Valori dei parametri
Parameter | Description |
---|---|
message | Optional. A string describing why the exception was thrown |
code | Optional. An integer that can be used used to easily distinguish this exception from others of the same type |
previous | Optional. If this exception was thrown in a catch block of another exception, it is recommended to pass that exception into this parameter |
Metodi
Quando si rileva un'eccezione, la tabella seguente mostra alcuni dei metodi che possono essere utilizzati per ottenere informazioni sull'eccezione:
Method | Description |
---|---|
getMessage() | Returns a string describing why the exception was thrown |
getPrevious() | If this exception was triggered by another one, this method returns the previous exception. If not, then it returns null |
getCode() | Returns the exception code |
getFile() | Returns the full path of the file in which the exception was thrown |
getLine() | Returns the line number of the line of code which threw the exception |
Esempio
Informazioni sull'output su un'eccezione generata:
<?php
function divide($dividend, $divisor) {
if($divisor == 0)
{
throw new Exception("Division by zero", 1);
}
return $dividend / $divisor;
}
try {
echo
divide(5, 0);
} catch(Exception $ex) {
$code = $ex->getCode();
$message = $ex->getMessage();
$file = $ex->getFile();
$line = $ex->getLine();
echo "Exception thrown in $file on line
$line: [Code $code]
$message";
}
?>
Riferimento completo alle eccezioni
Per un riferimento completo, vai al nostro Riferimento completo per le eccezioni PHP .
Il riferimento contiene descrizioni ed esempi di tutti i metodi di eccezione.