How does PHP throw exception handling errors

  • 2020-03-31 21:35:39
  • OfStack

The first thing to know is what is a PHP exception?

Exceptions are used to change the normal flow of the script when a specified error occurs.
PHP 5 provides a new object-oriented approach to error handling.
Exception handling is used to change the normal flow of the script when a specified error (exception) condition occurs. This condition is called an exception.

When an exception is triggered, it usually happens:

The current code state is saved
Code execution is switched to one of the predefined exception handler functions
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 location in the code
We will show different error handling methods:

The basic use of exceptions
Create a custom exception handler
Multiple abnormal
Rethrow an exception
Set the top-level exception handler
The basic use of exceptions
When an exception is thrown, the subsequent code does not continue to execute, and PHP tries to find a matching block of "catch" code.

If the Exception is not caught and is not handled using set_exception_handler(), a serious error (fatal error) occurs and an error message of "Uncaught Exception" is printed.

Let's try to throw an exception without catching it:
 
<?php 
//create function with an exceptionfunction 
checkNum($number) { 
if($number>1) { 
throw new Exception( " Value must be 1 or below " ); 
} return true; 
} 
//trigger 
exceptioncheckNum(2); 
?> 

The above code will get an error like this:

Fatal error: Uncaught exception 'exception' with message 'Value must be 1 or below' in C:\webfolder\test.php:6 Stack trace: #0 C:\webfolder\test.php(12): CheckNum (28) #1 {main} thrown in C:\webfolder\test.php on line 6
Try to throw and catch
To avoid the errors in the above example, we need to create the appropriate code to handle exceptions.

Processing procedures shall include:

Try - functions that use exceptions should be in the "Try" code block. If no exception is fired, the code continues to execute as usual. But if an exception is fired, an exception is thrown.
Throw - this specifies how to trigger an exception. Every throw must correspond to at least one catch.
The Catch - "Catch" block catches the exception and creates an object that contains the exception information
Let's fire an exception:

< ? PHP // create function checkNum($number) {if($number> 1) {throw new Exception(" Value must be 1 or below "); } return true; }// in the "try" block of code to trigger the exception try {checkNum(2); //If the exception is thrown, this text will not be shown echo 'If you see this, the number is 1 or below'; }// catch Exception (Exception $e) {echo 'Message:'. GetMessage (); }? >
The above code will get an error like this:

Message: Value must be 1 or below
Example explanation:
The above code throws an exception and catches it:

Create the checkNum() function. It detects if the number is greater than 1. If so, an exception is thrown.
The checkNum() function is called in the "try" code block.
The exception in the checkNum() function is thrown
The "catch" block receives the exception and creates an object ($e) that contains the exception information.
By calling $e-> from this exception object; GetMessage (), which outputs an error message from the exception
However, to follow the catch per throw rule, you can set up a top-level exception handler to handle missed errors.
Create a custom Exception class
Creating a custom exception handler is simple. We simply created a specialized class that can be called when an exception occurs in PHP. This class must be an extension of the exception class.

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

We start to create the exception class:
 
<?php 
class customException extends Exception { 
public function errorMessage() { 
//error message 
$errorMsg =  ' Error on line  ' .$this->getLine().' in  ' .$this->getFile() .': <b>'.$this->getMessage().'</b> is not a valid E-Mail address'; return $errorMsg; 
} 
} 
$email =  " someone@example ... com " ;try { 
//check if 
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(); 
}?> 

This new class is a copy of the old exception class, plus the errorMessage() function. Since it is a copy of the old class, so it inherits properties and methods from the old class, we can use the 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:

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 class.
Create the errorMessage() function. If the E-mail address is illegal, the function returns an error message
Set the $email variable to an invalid E-mail address string
Execute the "try" block of code and throw an exception because the E-mail address is invalid
The "catch" block catches the exception and displays the error message
Multiple abnormal
You can use multiple exceptions for a script to detect multiple situations.

You can use multiple if.. Else code block, or a switch code block, or nested 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 on line  ' .$this->getLine().' in  ' .$this->getFile().': <b>'.$this->getMessage().'</b> is not a valid E-Mail address'; 
return $errorMsg; 
} 
} 
$email =  " someone@example.com " ;try { 
//check if 
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 is an example e-mail " ); } }catch (customException $e) { echo $e->errorMessage(); }catch(Exception $e) { echo $e->getMessage(); }?> 

Example explanation:
The above code tests both conditions, and throws an exception if either condition fails:

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 class.
Create the errorMessage() function. If the E-mail address is illegal, the function returns an error message.
Execute the "try" block of code without throwing an exception under the first condition.
Because the E-mail contains the string "example," the second condition triggers an exception.
The "catch" block catches the exception and displays the appropriate error message
If the customException is not caught and the base exception is caught tightly, the exception is handled there.
Rethrow an exception
Sometimes, when an exception is thrown, you might want to handle it differently from the standard. You can throw an exception again in a "catch" code block.

Scripts should hide system errors from users. System errors may be important to programmers, but they are not of interest to users. To make it easier for users to use, you can again throw an exception with a more user-friendly message:
 
<?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 code above checks for the string "example" in the email address. If so, throw an exception again:

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 class.
Create the errorMessage() function. If the E-mail address is illegal, the function returns an error message.
Set the $email variable to a valid email address, but with the string "example."
The "try" code block contains another "try" code block so that the exception can be thrown again.
Because the E-mail contains the string "example," an exception is fired.
"Catch" catches the exception and throws a "customException" again.
The "customException" is caught and an error message is displayed.
If the exception is not caught in its current "try" block, it looks for the catch block at a higher level.
Set the Top Level Exception Handler
The set_exception_handler() function sets the 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 should look like this:

Exception: Uncaught Exception occurred
In the above code, there is no "catch" block of code, but instead the top-level exception handler is triggered. This function should be used to catch all uncaught exceptions.
Rule of exception
Code that requires exception handling should be placed in a try code block to catch potential exceptions.
Each try or throw block must have at least one catch block.
Using multiple catch code blocks can catch different kinds of exceptions.
You can throw a (re-thrown) exception again in the catch code block within the try code block.
In short: if an exception is thrown, it must be caught.

Related articles: