EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

PHP Custom Exception

Home » Software Development » Software Development Tutorials » PHP Tutorial » PHP Custom Exception

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:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

  • 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:

Popular Course in this category
PHP Training (5 Courses, 3 Project)5 Online Courses | 3 Hands-on Project | 28+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (5,678 ratings)
Course Price

View Course

Related Courses
Java Servlet Training (6 Courses, 12 Projects)All in One Software Development Bundle (600+ Courses, 50+ projects)

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;
}

Output:

PHP Custom Exception 1

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:

<?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:

php custom exception 3

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()

PHP Training (5 Courses, 3 Project)

5 Online Courses

3 Hands-on Project

28+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
PHP Tutorial
  • Advanced
    • Overloading in PHP
    • Overriding in PHP
    • Method Overloading in PHP
    • Inheritance in PHP
    • Multiple Inheritance in PHP
    • PHP Interface
    • Encapsulation in PHP
    • PHP Constants
    • PHP Magic Constants
    • PHP Regular Expressions
    • PHP GET Method
    • PHP Annotations
    • PHP Encryption
    • PHP file Functions
    • PHP readfile
    • PHP?Write File
    • PHP Append File
    • PHP Type Hinting
    • PHP Filters
    • PHP Float
    • PHP Form
    • PHP Form Validation
    • Sorting in PHP
    • PHP usort()
    • PHP Stack Trace
    • PHP Stack Overflow
    • PHP Pagination
    • PHP implode
    • Polymorphism in PHP
    • Abstract Class in PHP
    • PHP Final Class
    • PHP Custom Exception
    • error_reporting() in PHP
    • PHP Log Errors
    • Access Modifiers in PHP
    • PHP Change Date Format
    • Static Method in PHP
    • PHP File Handling
    • PHP Output Buffering
    • Get IP Address in PHP
    • Upload a File in PHP
    • String in PHP
    • Public Function in PHP
    • Private in PHP
    • Protected in PHP
    • basename in PHP
    • Validation in PHP
    • PHP mail()
    • PHP Email Form
    • PHP Directory
    • PHP Create Session
    • PHP include_once
    • PHP json_decode
    • PHP XMLWriter
    • PHP XML Reader
    • PHP XML Parser
    • PHP XML into Array
    • Phalcon Framework
  • PHP Basic
    • Introduction To PHP
    • What is PHP
    • PHP Keywords
    • Advantages of PHP
    • Career In PHP
    • Comments in PHP
    • PHP Commands
    • PHP Frameworks
    • PHP Compiler
    • Variables in PHP
    • PHP Superglobal Variables
    • PHP Versions
    • Object in PHP
    • What is Drupal
    • Top PHP Frameworks
    • WebStorm IDE
    • What is phpMyAdmin?
    • PhpStorm
    • Install phpMyAdmin
    • Phalcon Model
  • Data Types
    • PHP Data Types
    • PHP Integer
    • PHP Booleans
  • Operators
    • PHP Operators
    • Arithmetic Operators in PHP
    • Comparison Operators in PHP
    • Logical Operators in PHP
    • Bitwise Operators in PHP
    • Ternary Operator in PHP
    • PHP String Operators
  • Control Statements
    • Control Statement in PHP
    • PHP if Statement
    • if else Statement in PHP
    • elseif in PHP
    • PHP Switch Statement
    • Continue in PHP
    • Break in PHP
  • Loops
    • PHP Loops
    • For Loop in PHP
    • PHP Do While Loop
    • PHP While Loop
    • While Loop in PHP
    • Foreach Loop in PHP
  • Constructor
    • Constructor in PHP
    • Destructor in PHP
  • State Management
    • Cookie in PHP
    • Sessions in PHP
  • Array
    • What is PHP Array
    • Arrays in PHP
    • 2D Arrays in PHP
    • Associative Array in PHP 
    • Multidimensional Array in PHP
    • Indexed Array in PHP
    • PHP Array Functions
    • PHP unset Array
    • PHP Append Array
    • PHP Array Search
    • PHP Split Array
    • PHP array_push()
    • PHP array_pop()
  • Functions
    • Functions in PHP
    • PHP Math Functions
    • PHP Recursive Function
    • PHP String Functions
    • Hashing Function in PHP
    • Date Function in PHP
    • PHP Anonymous Function
    • Calendar in PHP
    • PHP Call Function
    • PHP Pass by Reference
    • PHP ucfirst()
    • PHP ucwords()
    • trim() in PHP
    • isset() Function in PHP
    • PHP replace
    • PHP fpm
    • PHP strpos
    • preg_match in PHP
    • PHP preg_replace()
    • PHP ob_start()
    • PHP Reflection
    • PHP Split String
    • PHP URL
    • PHP preg_match_all
    • PHP strtoupper()
    • PHP preg_split()
    • PHP substr_replace()
    • PHP setlocale()
    • PHP substr_count()
    • PHP Serialize
    • PHP strlen()
    • PHP async
    • PHP Date Time Functions
    • PHP timezone
    • PHP Data Object
    • print_r() in PHP
    • PHP header()
    • PHP strip_tags()
    • PHP chop()
    • PHP MD5()
    • PHP unset()
    • PHP crypt()
    • PHP wordwrap()
    • PHP is_null()
    • PHP strtok()
    • PHP bin2hex()
    • PHP parse_str()
    • PHP levenshtein()
    • PHP addslashes()
    • PHP strtotime
    • PHP sha1()
    • PHP explode()
    • PHP sscanf()
    • PHP require_once
    • PHP Zip Files
    • PHP $_SERVER
    • PHP $_POST
    • PHP Include and Require
    • PHP POST Method
  • Programs
    • Patterns in PHP
    • Star Patterns in PHP
    • Swapping in PHP
    • Fibonacci Series PHP
    • Factorial in PHP
    • Reverse String in PHP
    • Square Root in PHP
    • Random Number Generator in PHP
    • Palindrome in PHP
    • Prime Numbers in PHP
    • Armstrong Number in PHP
    • Socket Programming in PHP
    • Login Page in PHP
    • PHP Login Template
    • PHP Object to String
  • Database
    • PHP Database Connection
    • How to Connect Database to PHP
  • Interview Questions
    • PHP Interview Questions
    • PHP OOP Interview Questions
    • CakePHP Interview Questions
    • Core PHP Interview Questions

Related Courses

PHP Training Course

Java Servlet Training

Software Development Course Training

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - PHP Training (5 Courses, 3 Project) Learn More