Federico Cargnelutti

Simple is better than complex. Complex is better than complicated. | @fedecarg

Extending Exceptions

with one comment

So far, one of the problems with the exception system is all of the exceptions are instances of the same class that only differ by the message they display. This gives us little chance to distinguish between different errors, especially if we localize the error messages into different languages.

It would be beneficial for you to create subclasses of the Exception class that you can then check in code to learn more about the nature of the error:

<?php

class ArgumentTypeException extends Exception
{
	function __construct($in_type, $in_expected)
	{
		parent::__construct("Expected: $in_expected, Received: $in_type");
	}
}

class ArgumentRangeException extends Exception
{
	function __construct($in_value, $in_bottom, $in_top)
	{
		$msg = "Value $in_value was not in the range $in_bottom .. $in_top";
		parent::__construct($msg);
	}
}

?>

Now, you can call the getUserId() function that will give you more information in case of a failure.

<?php

function getUserId($id)
{
	if (!is_int($id)) {
		throw new ArgumentTypeException(gettype($id), 'int');
	}

	if ($id < 0 || $id > 6) {
		throw new ArgumentRangeException($id, 0, 6);
	}
}

getUserId(null);
getUserId(8);

?>

Return Values

Fatal error: Uncaught exception 'ArgumentTypeException' with message 'Expected: int,
Received: NULL' in test.php:22 Stack trace: #0 test.php(30): getUserId(NULL) #1 {
main} thrown in test.php on line 22

Fatal error: Uncaught exception 'ArgumentRangeException' with message
'Value 8 was not in the range 0 .. 6' in test.php:26 Stack trace:
#0 test.php(30): getUserId(8) #1 {main} thrown in test.php on line 26

See also: Extending Exceptions

Written by Federico

April 3, 2007 at 11:02 pm

Posted in PHP

One Response

Subscribe to comments with RSS.


Leave a Reply