Why not just extend Exception
? Something like this ...
namespace ProjectName\Exceptions\SpecialException;
class SpecialException extends Exception
{
// Implement custom properties and methods if required. Optional.
}
Here we have a custom class that uses SpecialException
:
use \ProjectName\Exceptions\SpecialException;
class DocumentRepository
{
public static function fetchByID($docID)
{
throw new SpecialException("Document does not exist");
}
}
And now you don't need to worry about whether or not SpecialException
exists or not. If calling code throws a regular Exception
it will get caught, but if it throws a SpecialException
it will still get caught as the new exceptions base class is Exception
.
try
{
$doc = DocumentRepository::fetchByID(12);
}
catch(Exception $e)
{
die($e->getMessage());
}
Or, if you want to catch the SpecialException
you can do (and I highly recommend this):
try
{
$doc = DocumentRepository::fetchByID(12);
}
catch(SpecialException $e)
{
die($e->getMessage());
}
Update to answer the problem in your comment
As a developer using a framework you have a location where you store your custom classes, files etc. right? Let me assume that this location is ProjectName/lib
. And lets assume the framework you're using lives in the directory ProjectName/BaseFramework
.
Your custom SpecialException
will live in ProjectName/lib/Exceptions/SpecialException.php
.
Currently, the framework doesn't include this exception. So in the files you wish to use SpecialException
you use the following use
line:
use \ProjectName\Exceptions\SpecialException
When the framework finally does implement this SpecialException
you simply replace that use
line with this one:
use \BaseProject\Exceptions\SpecialException
It's as simple as that.
If you try to do this in the way other users have suggested you will have dead code in your system. When SpecialException
is finally implemented the checks on which type of Exception
to use will be redundant.
This assumes you're using something like composer or something else that handles autoloading.