May 11, 2021 PHP
3. The basic use of exceptions
6. Create a custom Exception class
10.. Throw the exception again
Exceptions are used to change the normal flow of the script when a specified error occurs.
PHP 5 provides a new way to handle object-oriented errors.
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 occurs:
We'll show you different ways to handle errors:
Note: Exceptions should only be used in the wrong situation and should not be used to jump to another location in the code at a specified point.
When an exception is thrown, the subsequent code does not continue and PHP attempts to find a matching "catch" block of code.
If the exception is not caught and set_exception_handler() is not handled accordingly, a serious error (fatal error) occurs and an error message is output for "Uncaught Exception" (uncaught exception).
Let's try to throw an exception without catching it:
<?php
//create function with an exception
function checkNum($number)
{
if($number>1)
{
throw new Exception("Value must be 1 or below");
}
return true;
}
//trigger exception
checkNum(2);
?>
The above code gets an error like this:
To avoid errors in the above instance, we need to create the appropriate code to handle the exception.
The appropriate handling exception code should include:
Let's trigger an exception:
<?php
//create function with an exception
function checkNum($number)
{
if($number>1)
{
throw new Exception("Value must be 1 or below");
}
return true;
}
//trigger exception in a "try" block
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
catch(Exception $e)
{
echo 'Message: ' .$e->getMessage();
}
?>
The above code will get an error like this:
The above code throws an exception and catches it:
However, in order to follow the "one catch per throw" principle, you can set up a top-level exception processor to handle missed errors.
Creating custom exception handlers is easy. W e simply created a specialized class that can call its functions when an exception occurs in PHP. The 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.
Let's start creating 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 = "[email protected]";
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. Just because it's a copy of the old class, so it inherits properties and methods from the old class, we can use methods of the exception class, such as getLine(), getFile(), and getMessage().
The above code throws an exception and catches it with a custom exception class:
You can use multiple exceptions for a single script to detect multiple situations.
You can use more than one if: . E lse blocks of code, or a switch block of code, or nesting 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 on line '.$this->getLine().' in '.$this->getFile()
.': <b>'.$this->getMessage().'</b> is not a valid E-Mail address';
return $errorMsg;
}
}
$email = "[email protected]";
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();
}
?>
The above code tests two conditions and throws an exception if neither of them is true:
If the customException class throws an exception, but does not catch customException, and only base exception is caught, the exception is handled there.
Sometimes, when an exception is thrown, you may want to handle it in a different way than the standard. You can throw an exception again in a "catch" block of code.
The script should hide system errors from the user. S ystem errors may be important to programmers, but users are not interested in them. To make it easier for users to use, you can again 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 = "[email protected]";
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();
}
?>
The code above detects whether the string "example" is in the email address. If so, throw the exception again:
If the exception is not caught in the current "try" block, it looks for the catch block at a higher level.
set_exception_handler() functions set up user-defined functions to handle all uncosted 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 looks like this:
In the code above, there is no "catch" block of code, but rather an exception handler that triggers the top level.
You should use this function to catch all uncaught exceptions.
In short: if an exception is thrown, it must be caught.
In the next section, we'll take a look at the use of PHP filters.