Esercitazione PHP

PHP HOME Introduzione a PHP Installazione PHP Sintassi PHP Commenti PHP Variabili PHP PHP Eco/Stampa Tipi di dati PHP Stringhe PHP Numeri PHP PHP matematica Costanti PHP Operatori PHP PHP Se...Altro...Altro Passaggio PHP Ciclo PHP Funzioni PHP Matrici PHP Superglobali PHP RegEx PHP

Moduli PHP

Gestione dei moduli PHP Convalida del modulo PHP Modulo PHP richiesto URL/e-mail del modulo PHP Modulo PHP completo

PHP avanzato

Data e ora PHP PHP Include Gestione dei file PHP Apri/Leggi file PHP Creazione/scrittura di file PHP Caricamento file PHP Cookie PHP Sessioni PHP Filtri PHP Filtri PHP avanzati Funzioni di callback PHP PHP JSON Eccezioni PHP

PHP OOP

PHP Che cos'è OOP Classi/Oggetti PHP Costruttore PHP PHP distruttore Modificatori di accesso PHP Ereditarietà PHP Costanti PHP Classi astratte PHP Interfacce PHP Tratti PHP Metodi statici PHP Proprietà statiche PHP Spazi dei nomi PHP Iterabili PHP

Database MySQL

Database MySQL MySQL Connect MySQL Crea DB MySQL Crea tabella Dati di inserimento MySQL MySQL Ottieni l'ultimo ID MySQL inserisce più MySQL preparato MySQL Seleziona dati MySQL dove MySQL Ordina per MySQL Elimina dati Dati di aggiornamento MySQL Dati limite MySQL

PHP XML

Parser XML PHP Analizzatore PHP SimpleXML PHP SimpleXML - Ottieni PHP XML espatriato PHP XML DOM

PHP - AJAX

Introduzione all'Ajax AJAX PHP Database AJAX XML AJAX Ricerca in tempo reale AJAX Sondaggio AJAX

Esempi PHP

Esempi PHP compilatore PHP Quiz PHP Esercizi PHP Certificato PHP

Riferimento PHP

Panoramica di PHP matrice PHP Calendario PHP Data PHP Directory PHP Errore PHP Eccezione PHP File system PHP Filtro PHP PHP FTP PHP JSON Parole chiave PHP PHP Libxml Posta PHP PHP matematica PHP Varie PHP MySQLi Rete PHP Controllo dell'output PHP RegEx PHP PHP SimpleXML Flusso PHP Stringa PHP Gestione delle variabili PHP Analizzatore XML PHP Zip PHP Fuso orario PHP

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' throwistruzione 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...catchistruzione 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 è Exceptione il nome della variabile è $e.


La prova... la cattura... finalmente la dichiarazione

L' try...catch...finallyistruzione può essere utilizzata per catturare le eccezioni. Il codice nel finallyblocco verrà sempre eseguito indipendentemente dal fatto che sia stata rilevata un'eccezione. Se finallyè presente, il catchblocco è 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.