Reputation: 10908
I am writing some new code in which I want to use some self defined exceptions. For instance TableCreationFailedException
. Since I'm using PHP the base class this is deriving from is the Exception
class.
In case of this particular exception it needs to hold the table which could not be created.
I'm wondering how to best have this table field in the exception be set. A required argument in the constructor seems the way to go. Do I put the new argument at the front of the argument list? Shall I drop the message and arguments if I do not expect them to be needed? What are the conventions here, if any?
Upvotes: 1
Views: 65
Reputation: 173542
There are no hard and fast rules; something like this would work just fine:
class TableCreationFailedException extends \Exception
{
public function __construct($table, \Exception $previous = null)
{
parent::__construct("Table $table could not be created", 0, $previous);
}
}
In your case I would put the specialized argument $table
in front of the ones the parent Exception constructor would accept.
It's also advisable to make sure you can chain exceptions together by adding $previous
to the constructor arguments.
I've left out $code
, which is now hardcoded as 0
; you could add it like this:
public function __construct($table, $code = 0, \Exception $previous = null)
{
parent::__construct("Table $table could not be created", $code, $previous);
}
Upvotes: 2