PHP-undantagshantering
- Föregående sida PHP Error
- Nästa sida PHP Filter
Undantag (Exception) används för att ändra skriptets normala flöde vid specifika fel.
Vad är ett undantag?
PHP 5 erbjuder ett nytt objektorienterat felhanteringsmethos.
Undantagshantering används för att ändra skriptets normala flöde vid specifika fel (undantag). Detta kallas ett undantag.
När ett undantag utlöses, inträffar vanligtvis:
- Aktuell kodstatus sparas
- Kodexekveringen växlas till en fördefinierad undantagshanterarfunktion
- Beroende på situationen kan hanteraren starta om koden från ett bevarat kodstånd, avsluta skriptets körning eller fortsätta skriptet från ett annat ställe i koden
Vi kommer att visa olika felhanteringsmetoder:
- Grundläggande användning av undantag
- Skapa en anpassad undantagshanterare
- Flera undantag
- Återkasta undantag
- Ställ in toppundantagshanterare
Grundläggande användning av undantag
När ett undantag kastas, fortsätter koden inte att köra, PHP försöker hitta en matchande "catch"-block.
Om undantaget inte fångas och det inte används set_exception_handler() för att hantera det, inträffar en allvarlig fel (fatalt fel) och meddelandet "Ej fångad Exception" (ej fångad undantag) skrivs ut.
Låt oss försöka kasta ett undantag utan att fånga det:
<?php //skapa funktion med ett undantag function checkNum($number) { if($number>1) { throw new Exception("Värdet måste vara 1 eller lägre"); } return true; } //utlösa undantag checkNum(2); ?>
Ovanstående kod kommer att ge ett fel liknande detta:
Fatalt fel: Ej fångad undantag 'Exception' med meddelandet 'Value must be 1 or below' i C:\webfolder\test.php:6 Stack trace: #0 C:\webfolder\test.php(12): checkNum(28) #1 {main} kastades i C:\webfolder\test.php på rad 6
Try, throw och catch
För att undvika fel som uppstår i ovanstående exempel, behöver vi skapa lämplig kod för att hantera undantag.
En korrekt hanterare bör inkludera:
- Försök - Funktioner som kastar undantag bör placeras inom en "försök"-block. Om inget undantag utlöses, kommer koden att fortsätta att köra som vanligt. Men om ett undantag utlöses, kastas ett undantag.
- Throw - Här definieras hur undantag utlöses. Varje "throw" måste ha minst en "catch"
- Catch - "catch"-blocket fångar undantaget och skapar ett objekt som innehåller undantagsinformation
Låt oss utlösa ett undantag:
<?php //Skapa en funktion som kan kasta ett undantag function checkNum($number) { if($number>1) { throw new Exception("Värdet måste vara 1 eller lägre"); } return true; } //Upprättar undantag i "try"-blocket try { checkNum(2); //Om undantaget kastas, kommer denna text inte att visas echo 'Om du ser detta, är numret 1 eller lägre'; } //Fångar undantag catch(Exception $e) { echo 'Meddelande: ' .$e->getMessage(); } ?>
Ovanstående kod kommer att ge ett fel liknande detta:
Meddelande: Värdet måste vara 1 eller lägre
Example explanation:
Ovanstående kod kastar ut ett undantag och fångar det:
- Skapa checkNum()-funktionen. Den kontrollerar om ett nummer är större än 1. Om det är sådant, kastas ett undantag ut.
- Anropa checkNum()-funktionen i "try"-blocket.
- Undantaget i checkNum()-funktionen kastas ut.
- "catch"-blocket tar emot detta undantag och skapar ett objekt som innehåller undantagsinformation ($e).
- Genom att anropa $e->getMessage() från detta exception-objekt, skrivs ut felmeddelandet från undantaget.
För att följa principen "varje throw måste ha en catch", kan du ställa in en toppnivå-undantagshanterare för att hantera övergivna fel.
Skapa en anpassad Exception-klass
Att skapa en anpassad exception-handlare är mycket enkelt. Vi skapar enkelt en dedikerad klass som kan anropas när ett undantag inträffar i PHP. Denna klass måste vara en utökning av exception-klassen.
Denna anpassade exception-klass ärver alla egenskaper från PHP:s exception-klass, och du kan lägga till egna funktioner till den.
Vi börjar skapa en exception-klass:
<?php class customException extends Exception { public function errorMessage() { //error message $errorMsg = 'Fel på rad '.$this->getLine().' i '.$this->getFile(); ': <b>'.$this->getMessage().'</b> är inte en giltig E-postadress'; return $errorMsg; } } $email = "someone@example...com"; try { //kontrollera om if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) { //throw exception if email is not valid throw new customException($email); } } catch (customException $e) { //display custom message echo $e->errorMessage(); } ?>
这个新的类是旧的 exception 类的副本,外加 errorMessage() 函数。正因为它是旧类的副本,因此它从旧类继承了属性和方法,我们可以使用 exception 类的方法,比如 getLine() 、 getFile() 以及 getMessage()。
Example explanation:
Ovanstående kod kastar ett undantag och fångar det med en anpassad exception-klass:
- The customException() class was created as an extension of the old exception class. This way, it inherits all properties and methods of the old class.
- Skapa errorMessage()-funktionen. Om e-postadressen är ogiltig, returnerar denna funktion ett felmeddelande
- Sätt $email-variabeln till en ogiltig e-postadresssträng
- Kör "try"-blocket, ett undantag kastas på grund av att e-postadressen är ogiltig
- En "catch"-block fångar undantag och visar felmeddelanden
Flera undantag
Det är möjligt att använda flera undantag för ett skript för att kontrollera flera situationer.
Det är möjligt att använda flera if..else-block eller ett switch-block, eller att nästla flera undantag. Dessa undantag kan använda olika exception-klasser och returnera olika felmeddelanden:
<?php class customException extends Exception { public function errorMessage() { //error message $errorMsg = 'Fel på rad '.$this->getLine().' i '.$this->getFile(); ': <b>'.$this->getMessage().'</b> är inte en giltig E-postadress'; return $errorMsg; } } $email = "someone@example.com"; try { //kontrollera om if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) { //throw exception if email is not valid throw new customException($email); } //check for "example" in mail address if(strpos($email, "example") !== FALSE) { throw new Exception("$email är en example e-post"); } } catch (customException $e) { echo $e->errorMessage(); } catch(Exception $e) { echo $e->getMessage(); } ?>
Example explanation:
Ovanstående kod testar två villkor, och om något av villkoren inte är uppfyllt, kastas ett undantag:
- The customException() class was created as an extension of the old exception class. This way, it inherits all properties and methods of the old class.
- Created the errorMessage() function. If the e-mail address is not valid, this function returns an error message.
- Kör "try"-blocket, utan att kasta undantag vid den första villkoret.
- Eftersom e-post innehåller字符串 "example", kommer den andra villkoret att trigga undantaget.
- En "catch"-block fångar undantag och visar lämpliga felmeddelanden
Om du inte fångar customException men endast fångar base exception, hantera undantaget där.
Återkasta undantag
Ibland, när ett undantag kastas, kanske du vill behandla det på ett sätt som skiljer sig från det standardmässiga. Det är möjligt att kasta undantaget igen i en "catch"-block.
The script should hide system errors from the user. For programmers, system errors may be important, but users are not interested in them. To make it easier for users, you can re-throw exceptions with user-friendly messages:
<?php class customException extends Exception { public function errorMessage() { //error message $errorMsg = $this->getMessage().' is not a valid E-Mail address.'; return $errorMsg; } } $email = "someone@example.com"; try { try { //check for "example" in mail address if(strpos($email, "example") !== FALSE) { //throw exception if email is not valid throw new Exception($email); } } catch(Exception $e) { //re-throw exception throw new customException($email); } } catch (customException $e) { //display custom message echo $e->errorMessage(); } ?>
Example explanation:
The above code checks if the string "example" is present in the e-mail address. If it is, it throws the exception again:
- The customException() class was created as an extension of the old exception class. This way, it inherits all properties and methods of the old class.
- Created the errorMessage() function. If the e-mail address is not valid, this function returns an error message.
- Set the $email variable to a valid e-mail address, but it contains the string "example".
- The "try" block contains another "try" block, allowing the exception to be thrown again.
- An exception was triggered because the e-mail contains the string "example".
- "catch" caught the exception and re-threw "customException".
- Captured "customException" and displayed an error message.
Om undantaget inte fångas i den aktuella "try"-blocken, kommer det att leta efter en catch-block på en högre nivå.
Ställ in toppnivå undantagshanterare (Top Level Exception Handler)
set_exception_handler()-funktionen kan ställa in en användardefinierad funktion för att hantera alla inte fångade undantag.
<?php function myException($exception) { echo "<b>Exception:</b> " , $exception->getMessage(); } set_exception_handler('myException'); throw new Exception('Uncaught Exception occurred'); ?>
Uppgiften från ovanstående kod bör likna följande:
Exception: Uncaught Exception occurred
I ovanstående kod finns det ingen catch-block, utan undantagshanteringen på toppnivå aktiveras. Denna funktion bör användas för att fånga alla inte fångade undantag.
Undantagsregler
- Kod som behöver hantera undantag bör placeras inom en try-block för att fånga potentiella undantag.
- Varje try- eller throw-block måste ha minst en motsvarande catch-block.
- Genom att använda flera catch-block kan olika typer av undantag fångas.
- Undantag kan kastas igen (re-thrown) inom en catch-block som finns inom en try-block.
Kort sagt: Om ett undantag kastas, måste det fångas.
- Föregående sida PHP Error
- Nästa sida PHP Filter