PHP Custom Exception

WBOY
Release: 2024-08-29 13:06:10
Original
403 people have browsed it

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 Tests

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Below are things take place when an exception occurs:

  • The present state of the code is first saved.
  • 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.
  • It 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 { }
Copy after login

With the above CustException class now created, we can throw a custom exception as below:

throw new \CustExcep\CustException('Insert an Exception message here');
Copy after login

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

Let’s see the working of this function by taking a few examples:

Example #1

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;
}
Copy after login

Output:

PHP Custom Exception

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 nonoptional. We set the exception message to some default text. Here we should ensure that all the parameters we are using are assigned properly. This leads to errors. We then create another function called custFunc() and define our custom exception message here.
  • We are using the 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:

<?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();
}
?>
Copy after login

Output:

PHP Custom Exception

Explanation:

  • In this message, we also get the 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; 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 they can target and catch exceptions 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.
  • It is useful for catching “uncaught” exceptions.

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.

The above is the detailed content of PHP Custom Exception. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!