<?php
class MyException extends Exception
{
public function __construct($message, $code = 0, Throwable $previous = null) {
parent::__construct($message, $code, $previous);
}
public function __toString() {
return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
}
public function customFunction() {
echo "A custom function for this type of exception\n";
}
}
class TestException
{
public $var;
const THROW_NONE = 0;
const THROW_CUSTOM = 1;
const THROW_DEFAULT = 2;
function __construct($avalue = self::THROW_NONE) {
switch ($avalue) {
case self::THROW_CUSTOM:
throw new MyException('1 is an invalid parameter', 5);
break;
case self::THROW_DEFAULT:
throw new Exception('2 is not allowed as a parameter', 6);
break;
default:
$this->var = $avalue;
break;
}
}
}
try {
$o = new TestException(TestException::THROW_CUSTOM);
} catch (MyException $e) {
echo "Caught my exception\n", $e;
$e->customFunction();
} catch (Exception $e) {
echo "Caught Default Exception\n", $e;
}
var_dump($o);
echo "\n\n";
try {
$o = new TestException(TestException::THROW_DEFAULT);
} catch (MyException $e) {
echo "Caught my exception\n", $e;
$e->customFunction();
} catch (Exception $e) {
echo "Caught Default Exception\n", $e;
}
var_dump($o);
echo "\n\n";
try {
$o = new TestException(TestException::THROW_CUSTOM);
} catch (Exception $e) {
echo "Default Exception caught\n", $e;
}
var_dump($o);
echo "\n\n";
try {
$o = new TestException();
} catch (Exception $e) {
echo "Default Exception caught\n", $e;
}
var_dump($o);
echo "\n\n";
?>