PHP

Extending Exceptions

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 ArgumentTypeExceptionextends 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

One thought on “Extending Exceptions

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s