PHP - Creating custom exception

Introduction

The following code extends Exception to create custom exception.

<?php 
     use Exception; 

     class InvalidIdException extends Exception { 
        public function __construct($message = null) { 
            $message = $message ?: 'Invalid id provided.'; 
            parent::__construct($message); 
        } 
     } 
...

The InvalidIdException class extends from the class Exception.

The constructor of the class takes an optional argument, $message.

The ?: operator is a shorter version of a conditional.

parent::__construct will invoke the parent's constructor.

We can use this new exception.

throw new InvalidIdException('Id cannot be a negative number.'); 

Related Topics