PHP Syntax OOP Exceptions Custom

 

- Info:

- This tutorial shows how to create custom Exception by extending base Exception class.

 

- Example:

- In this example we overload constructor and implement new function for retreiving custom error message.

- We had to implement getCustomMessage() since ee couldn't override final method getMessage().

- Creat PHP Console Application Test.php.

 

Test.php

<?php

//CUSTOM EXCEPTION CLASS.

class MyException extends Exception {

function __construct($email, $code) {

$this->notifyAdmin($email);

$this->code = $code;

}

function notifyAdmin($email) {

echo "Sending mail to " . $email . "\n";

}

function getCustomMessage() { //We couldn't override final method getMessage.

switch($this->getCode()) {

case 1: return "This is very nasty error.";

case 2: return "Don't wory to much about this error.";

}

}

}

//THROW CUSTOM EXCEPTION.

try {

throw new MyException("ivoronline@gmail.com", 2); //Custom constructor.

}

catch (MyException $e) {

echo $e->getCustomMessage(); //We couldn't override final method getMessage.

}

?>