WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

PHP Exception Handling

Exceptions are used to change the normal flow of a script when a specified error occurs.


What is the exception

PHP 5 provides a new object-oriented approach to error handling.

Exception handling is used to change the normal flow of a script when a specified error (exception) situation occurs. This situation is called anomaly.

When an exception is triggered, it usually happens:

  • Current code state is saved
  • Code execution is switched to a predefined (custom) exception handler function
  • Depending on the situation, the processor may restart the execution of the code from the saved code state, terminate the execution of the script, or continue the execution of the script from another place in the code

We will show different error handling methods:

  • Basic use of exceptions
  • Create a custom exception handler
  • Multiple exceptions
  • Rethrow exception
  • Set the top-level exception handler

Note: Exceptions should only be used in error situations and should not be used to jump to another location in the code at a specified point.


Basic use of exceptions

When an exception is thrown, the subsequent code will not continue executing, and PHP will try to find a matching "catch" code block.

If the exception is not caught and you do not use set_exception_handler () to handle it accordingly, a serious error (fatal error) will occur and an "Uncaught Exception" error message will be output.

Let's try to throw an exception without catching it:

<?php // Create a function with exception handling function checkNum($number) { if($number>1) { throw new Exception("Value must be 1 or below"); } return true; } // Trigger an exception checkNum(2); ?>

The above code will get an error similar to this:

Fatal error: Uncaught exception 'Exception' with message 'Value must be 1 or below' in /www/welookups/test/test.php:7 Stack trace: #0 /www/welookups/test/test.php(13): checkNum(2) #1 {main} thrown in /www/welookups/test/test.php on line 7

Try, throw, and catch

To avoid the errors in the example above, we need to create appropriate code to handle the exception.

The appropriate exception handling code should include:

  1. Try-The function that uses the exception should be inside a "try" block. If no exception is triggered, the code will continue execution as usual. But if an exception is triggered, an exception is thrown.
  2. Throw-specifies how to trigger an exception. Each "throw" must correspond to at least one "catch".
  3. Catch-The "catch" block catches exceptions and creates an object containing exception information.

Let's trigger an exception:

<?php // Create a function with exception handling function checkNum($number) { if($number>1) { throw new Exception("Variable value must be less than or equal to 1"); } return true; } // Trigger exception in try block try { checkNum(2); // If an exception is thrown, the following text will not be output echo ' If the content is output, the $ number variable'; } // Catch exception catch(Exception $e) { echo 'Message: ' .$e->getMessage(); } ?>

The above code will get an error similar to this:

  Message  :     The value of the variable must be less than or equal to     1  

Example explanation:

The above code throws an exception and catches it:

  1. Create a checkNum () function. It detects if the number is greater than 1. If so, an exception is thrown.
  2. Call the checkNum () function in a "try" block.
  3. An exception in the checkNum () function was thrown.
  4. The "catch" code block receives the exception and creates an object ($ e) containing the exception information.
  5. By calling from this exception object $e->getMessage(),Output an error message from the exception.

However, in order to follow the "one catch per throw" principle, you can set up a top-level exception handler to handle missing errors.


Create a custom Exception class

Creating a custom exception handler is very simple. We simply created a special class that can call its functions when an exception occurs in PHP. This class must be an extension of the exception class.

This custom customException class inherits all the properties of PHP's exception class, and you can add custom functions to it.

Let ’s create the customException class:

<?php class customException extends Exception { public function errorMessage() { // Error message $errorMsg = 'Error line number '.$this->getLine().' in '.$this->getFile() .': <b>'.$this->getMessage().'</b> Not a legal one E-Mail address'; return $errorMsg; } } $email = "someone@example...com"; try { // Detect mailboxes if ( filter_var < span class = "hl-brackets"> ( $ email , FILTER_VALIDATE_EMAIL ) === FALSE ) { // If it is an illegal email address, an exception is thrown throw new customException($email); } } catch (customException $e) { //display custom message echo $e->errorMessage(); } ?>

This new class is a copy of the old exception class, plus the errorMessage () function. Because it is a copy of the old class, it inherits properties and methods from the old class. We can use methods of the exception class, such as getLine (), getFile (), and getMessage ().

Example explanation:

The above code throws an exception and catches it with a custom exception class:

  1. The customException () class was created as an extension of the old exception class. This way it inherits all the properties and methods of the old exception class.
  2. Create the errorMessage () function. If the e-mail address is invalid, the function returns an error message.
  3. Set the $ email variable to an illegal e-mail address string.
  4. The "try" code block was executed. An exception was thrown because the e-mail address was invalid.
  5. The "catch" code block catches the exception and displays an error message.

Multiple exceptions

You can use multiple exceptions for a script to detect multiple conditions.

You can use multiple if..else blocks, or a switch block, or nest multiple exceptions. These exceptions can use different exception classes and return different error messages:

<?php class customException extends Exception { public function errorMessage() { // Error message $errorMsg = 'Error line number '.$this->getLine().' in '.$this->getFile() .': <b>'.$this->getMessage().'</b> Not a legal one E-Mail address'; return $errorMsg; } } $email = "someone@example.com"; try { // Detect mailbox if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) { // If it is an invalid email address, throw an exception throw new customException($email); } // Check if "example" is in the email address if(strpos($email, "example") !== FALSE) { throw new Exception("$email Is the example email "); } } catch (customException $e) { echo $e->errorMessage(); } catch(Exception $e) { echo $e->getMessage(); } ?>

Example explanation:

The above code tests two conditions. If any of these conditions are not met, an exception is thrown:

  1. The customException () class was created as an extension of the old exception class. This way it inherits all the properties and methods of the old exception class.
  2. Create the errorMessage () function. If the e-mail address is invalid, the function returns an error message.
  3. Set the $ email variable to a string that is a valid e-mail address but contains the string "example".
  4. The "try" block is executed, and under the first condition, no exception is thrown.
  5. Because e-mail contains the string "example", the second condition triggers an exception.
  6. The "catch" code block catches exceptions and displays appropriate error messages.

If the customException class throws an exception, but doesn't catch customException, only the base exception is caught, the exception is handled there.


Rethrow exception

Sometimes when an exception is thrown, you may want to handle it differently than the standard. You can throw an exception again in a "catch" block.

The script should hide system errors from the user. System errors may be important to programmers, but users are not interested in them. To make it easier for users, you can throw an exception again with a user-friendly message:

<?php class customException extends Exception { public function errorMessage() { // Error message $errorMsg = $this->getMessage().' Not a legal one E-Mail address。'; return $errorMsg; } } $email = "someone@example.com"; try { try { // Check if "example" is in the email address if(strpos($email, "example") !== FALSE) { // If it is an invalid email address, throw an exception throw new Exception($email); } } catch(Exception $e) { // Rethrow exception throw new customException($email); } } catch (customException $e) { // Display custom information echo $e->errorMessage(); } ?>

Example explanation:

The above code checks if the email address contains the string "example". If so, throw the exception again:

  1. The customException () class was created as an extension of the old exception class. This way it inherits all the properties and methods of the old exception class.
  2. Create the errorMessage () function. If the e-mail address is invalid, the function returns an error message.
  3. Set the $ email variable to a string that is a valid e-mail address but contains the string "example".
  4. The "try" code block contains another "try" code block so that an exception can be thrown again.
  5. The e-mail triggered the exception because it contains the string "example".
  6. The "catch" code block catches the exception and rethrows "customException".
  7. Caught "customException" with an error message.

If an exception is not caught in the current "try" block, it will look for a catch block at a higher level.


Set the top-level exception handler

set_exception_handler () function sets a user-defined function that handles all uncaught exceptions.

<?php function myException($exception) { echo "<b>Exception:</b> " , $exception->getMessage(); } set_exception_handler('myException'); throw new Exception('Uncaught Exception occurred'); ?>

The output of the above code is as follows:

Exception: Uncaught Exception occurred

In the code above, there is no "catch" block, but the top-level exception handler is triggered. This function should be used to catch all uncaught exceptions.


Exceptional rules

  • The code that needs exception handling should be placed in a try block to catch potential exceptions.
  • Every try or throw block must have at least one corresponding catch block.
  • Use multiple catch blocks to catch different kinds of exceptions.
  • Exceptions can be thrown (rethrown) in a catch block inside a try block.

In short: if an exception is thrown, you must catch it.