The normal flow of a script stops when an error takes place, and an exception can be used for changing the same. A user can custom define exceptions as per the requirement of either the library, company or our application by extending the exception class already built-in in the PHP codebase. Here we will see the properties and members, which all are within the reach of the child class, which fetches from the built-in exception class.
ADVERTISEMENT Popular Course in this category PHP DEVELOPER - Specialization | 8 Course Series | 3 Mock TestsStart Your Free Software Development Course
Web development, programming languages, Software testing & others
Below are things take place when an exception occurs:
Let us know why we need to custom certain exceptions apart from the built-in ones:
For a custom exception to be thrown, we should simply extend another class from the Exception class, which is already built in.
namespace CustExcep; class CustException extends \Exception { }
With the above CustException class now created, we can throw a custom exception as below:
throw new \CustExcep\CustException('Insert an Exception message here');
We can also customize this as required to override certain class properties like file, code, line, and its message or by using __toString() method to force this exception message to the format we have to work with.
Let’s see the working of this function by taking a few examples:
Code:
<?php /** * Here defining a class for custom exception */ class CustException extends Exception { // Here we are redefining the exception message so it is not optional public function __construct($exmsg, $val = 0, Exception $old = null) { // random code goes here $exmsg = 'Default'; // ensure assignment of all values correctly parent::__construct($exmsg, $val, $old); } // representing the custom string object public function __toString() { return __CLASS__ . ": [{$this->code}]: {$this->message}\n"; } public function custFunc() { echo "Insert any custom message here\n"; } } /** * This class to test the exception */ class ExceptionTest { public $var; const NO_EXCEPTION = 0; const CUST_EXCEPTION = 1; const DEF_EXCEPTION = 2; function __construct($val = self::NO_EXCEPTION) { switch ($val) { case self::CUST_EXCEPTION: // throw custom exception throw new CustException('1 is considered as invalid', 5); break; case self::DEF_EXCEPTION: // throw default one. throw new Exception('2 is considered an invalid parameter', 6); break; default: // Will not throw any exception and creates an object here $this->var = $val; break; } } } // Example 1 try { $new = new ExceptionTest(ExceptionTest::CUST_EXCEPTION); } catch (CustException $exp) { // This exception will be caught echo "Test custom exception is caught\n", $exp; $exp->custFunc(); } catch (Exception $exp) { // This is skipped echo "Default exception is caught here\n", $exp; }
Output:
Explanation:
Code:
<?php class custException extends Exception { public function custMsg() { //error message $errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile() .': <b>'.$this->getMessage().'</b> is not a valid password. Please enter a valid one.'; return $errorMsg; } } $pwd = "Password@123"; try { //validation if(filter_var($pwd, FILTER_VALIDATE_EMAIL) === FALSE) { //exception thrown if password invalid throw new custException($pwd); } } catch (custException $error) { //show custom error echo $error->custMsg(); } ?>
Output:
Explanation:
Given below are the advantages:
In this article, we saw the concept of custom defining and handling of exceptions. There are also other cases where this can be used, such as in try-catch block, by throwing multiple exceptions, re-throwing certain exceptions, setting a top-class exception handler, etc.
The above is the detailed content of PHP Custom Exception. For more information, please follow other related articles on the PHP Chinese website!