Blog

PHP 5 features: Exceptions

2008-03-25 10:18:59 by Martynas Jusevičius

A useful new feature in PHP 5 is exception handling via the try/throw/catch paradigm.

An exception may be thrown and caught. If an exception is thrown in code surrounded by try, the following statements will not be executed, and the exception will be handled by the first matching catch block. Each try has to have at least one corresponding catch, and multiple catch blocks can be defined to handle different types of exceptions. Normal execution continues after the last catch block.
The built-in Exception class can be extended and a user-defined exception class can be implemented.

Exceptions is a powerful construct which can be used to improve code but also easily abused. PHP5 Exception Use Guidelines defines one basic rule of thumb:

Exceptions should never be used as normal program flow. If removing all exception handling logic (try-catch statements) from the program, the remaining code should represent the "One True Path" -- the flow that would be executed in the absence of errors.
This requirement is equivalent to requiring that exceptions be thrown only on error conditions, and never in normal program states.

When developing with the DIY Framework, we are mostly using exceptions to indicate form validation or non-permitted access errors. Here is an example from a SettingsResource class which handles a page of user settings, which should be accessible only when the user is logged on:

public function doPost(Request $request, Response $response)
{
	$view = null;
	$parent = parent::doPost($request, $response);

	if ($parent != null) $view = $parent;
	else
	{
		try
		{
			if ($request->getSession()->getAttribute("user") instanceof GuestUser) throw new NoPermissionException();

			$view = new SettingsGeneralView($this);

			// ... some other code to save submitted settings
		}
		catch (NoPermissionException $e)
		{
			$response->sendRedirect(FrontEndMapping::getHost().LoginResource::getInstance()->getURI());
		}
	}

	return $view;
}

If the user in session is a guest user (not logged on), an exception is thrown, and a redirect to the login page follows.

Digg Digg this! del.icio.us del.icio.us!

Comments (19)

Old feature

2008-03-25 11:43:26 by Michał Mech

"A useful new feature in PHP 5 is exception handling" - exception handling is a new feauture in PHP5, but PHP5 is old. I has almost 4 years.
You should wrote this post long time ago :P

2008-03-25 13:01:28 by Martynas

Well, that's right. But it is still the current version as PHP 6 is not yet out :)

I believe that not so many people actually use these features although they are several years old. So the goal was to show and remind that they're there and they're useful :)

2008-03-25 14:23:28 by Erik Bauffman

You say that exceptions should never be used as a normal program flow, yet you redirect a user using an exception when he's not logged in. Exception == fatal error, something's really gone tits up & the execution stops here.

Erik,

2008-03-25 15:00:48 by Martynas

Well, I agree, not beeing logged in is not like handling a database crash or the like.

But I tend think the definition of an error is not so rigid, it depends how you look at it.

In this situation a normal program flow occurs when a user is logged in, and that is what is left if we remove try/throw/catch statements.
If he/she is not, then the execution has to stop, and that is what does here.

@Erik

2008-03-25 15:52:29 by Bill Karwin

Exceptions are not always fatal application errors -- otherwise there wouldn't be a catch().

Exceptions can be fatal errors at a class or method level though, meaning a certain operation could not be performed. The application has an opportunity to catch this exception and may attempt to recover, or make an alternative action, or at least report the exception in an appropriate way. Redirecting to a login screen is a form of the latter.

When people say don't use exceptions as flow control, they mean for example it's confusing to use exceptions as a kind of "goto" statement that can pop out of a function and resume execution in another method higher on the call stack. If you've programmed in C and used longjmp(), that's the kind of thing that is discouraged.

PHP6

2008-03-26 10:53:32 by Review

Yes, exception handling is not new but we waiting impatiently for PHP6 :)

Old, but still relevant

2008-03-26 17:08:08 by PHP Programmer

Thanks for the article! Exception handling is one of the reasons people have left PHP for languages such as Python or Ruby.

tzndpzr

2009-06-30 00:58:33 by tzndpzr

8CyepK <a href="http://kdpeknjebivo.com/">kdpeknjebivo</a>, [url=http://wakztwnszqbb.com/]wakztwnszqbb[/url], [link=http://pcmgknsekoxz.com/]pcmgknsekoxz[/link], http://gzufdkvdnnlg.com/

oquOSlSRx

2009-08-20 13:50:19 by fqxbdq

uYcx9X <a href="http://zaxsyrtaqcek.com/">zaxsyrtaqcek</a>, [url=http://cximebunjfej.com/]cximebunjfej[/url], [link=http://nfjeucxcygjx.com/]nfjeucxcygjx[/link], http://rpsibispvjol.com/

cartier jewelry

2010-07-24 12:18:56 by cartier jewelry

adxz v

http://www.passforsure.co.uk/000-081.htm

2010-08-04 08:11:34 by pass4sure 000-081

Amazing

http://www.passforsure.co.uk/JN0-331.htm

2010-08-04 08:11:50 by pass4sure JN0-331

lovely

http://www.passforsure.co.uk/642-359.htm

2010-08-04 08:12:11 by pass4sure 642-359

Nice one

http://www.passforsure.co.uk/646-230.htm

2010-08-04 08:12:28 by pass4sure 646-230

like

Thank you.This

2010-08-05 05:15:08 by ed Hardy Clothing

I found this post while surfing the web for freebies.There seemed to me something cheap ed hardy alarming in such easy delights. In my ed hardy sale heart was desire to live more ed hardy clothing dangerously. I was not unprepared for jagged herve leger dress rocks and treacherous, shoals it I could only have change-change and the http://www.edhardy-buy.com/ exicitement of unforeseen.Thanks for sharing this article.

Great article

2010-08-05 05:25:59 by cheap Jordans Shoes

Thank you for your insight,the article was worth every minute reading it.However mean your authentic jordan shoes life is,meet it and live it,do not shun it and call it cheap jordans shoes hard names.It is not so bad as you cheap nike shox are.It looks poorest when you are cheap nike shoes richest.The fault-finder will find faults in http://www.nikejordanshoes2sell.com/ paradise.

New model

2010-08-05 05:28:33 by christian Louboutin UK

Great article very helpful.Human felicity is produced christian louboutin shoes not so much by great pieces of good tory borch shoes fortune that seldom happen,as by little advantages that occur christian louboutin pumps every day.Happiness lies not in the mere possession of money it lies in the christian louboutin sale joy of achievement , in the thrill of creative http://www.christianlouboutinshoestore.com/ effort.

burberry handbags

2010-08-09 11:48:16 by burberry handbags

it is very good!

gucci handbags

2010-08-09 11:50:25 by gucci handbags

thank you!

New comment






No HTML allowed.