Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

PHP Custom Exception

Introduction to PHP Custom Exception

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 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. We shall also see SQL exceptions that can be used in coding.

Below things takes place when an exception occurs:

  • Present state of the code is first saved.
  • Execution of the code will be then switched to the custom defined exception handling function.
  • The exception handler will either continue executing from the saved state of the code, terminate its execution or continues the execution from another place of the code.

Let us know why we need to custom certain exceptions apart from the built-in ones:

  • We can easily recognize exactly which class, extension or string generates the exception in the hierarchy of the code.
  • By using this the developer can easily spot the issues in the code.
  • Can be used for branding certain library exceptions like DOM, PDO, etc.
  • We can configure as many custom exceptions as required.

Syntax of PHP Custom Exception

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.

Working of Custom Function in PHP

Lets see the working of this function by taking a few examples:

Example #1

Code:

/**
* 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:

  • In this example we shall see how to custom throw our exceptions. To do this, first we are defining a class for this purpose and in this we are redefining the exception message using a constructor to make it non optional. We set the exception message to some default text. Here we should make sure that all the parameters we are using are assigned properly else this leads to error. We are then creating another function called custFunc() and defining our custom exception message here.
  • To test this we are creating another class called ExceptionTest where we are further declaring 3 variables NO_EXCEPTION, CUST_EXCEPTION, DEF_EXCEPTION and assigning their values to 0, 1 and 2 respectively. We are using switch statement to define 3 different custom exceptions for these 3 values and in the default case it will not throw any exception and creates the required object.
  • To try this out we are trying to create a new object by passing the value as CUST_EXCEPTION. Here we will call our custFunc() method defined at the beginning. Hence this will fetch the exception message defined and display the same.

Example #2

Code:

class custException extends Exception {
public function custMsg() {
//error message
$errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile()
.': '.$this->getMessage().' 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:

  • In this example we are defining a method called custMsg() where we are displaying a custom error message to throw an error if a wrong password is entered.
  • In this message we are also getting line number to throw a proper error. We enter the password value and then compare it with VALIDATE_PWD. If this returns true, no exception is thrown and if the result is false it throws our custom exception.

Advantages of PHP Custom Exception

Given below are the advantages:

  • Built-in exceptions are good but custom exceptions have more importance from a developer’s point of view since it can target and catch exception wherever he wants.
  • Easy to debug as the developer can define custom exceptions at multiple points and handle the same.
  • Can easily modify the existing Exception class and use it in a more efficient way by extending it.
  • Is useful for catching “uncaught” exception.

Conclusion

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. These are basically used to avoid sudden errors and to continue the execution of code without any interference.

Recommended Articles

This is a guide to Php Custom Exception. Here we discuss the introduction to PHP Custom Exception, working of custom function along with respective advantages. You may also have a look at the following articles to learn more –

  1. PHP Append Array
  2. PHP unset Array
  3. PHP explode()
  4. PHP strtok()

The post PHP Custom Exception appeared first on EDUCBA.



This post first appeared on Best Online Training & Video Courses | EduCBA, please read the originial post: here

Share the post

PHP Custom Exception

×

Subscribe to Best Online Training & Video Courses | Educba

Get updates delivered right to your inbox!

Thank you for your subscription

×