I'm currently implementing PHP 5 exceptions in MediaWiki and I've come across a design question. How often should exceptions be used?
I've set up an exception handler which is quite capable of formatting and displaying pretty error messages for the user. The HTML to be displayed is defined by the exception class. But the question is, how often should I use them? Say if I have the choice between:
function deleteUserInterface( $file ) { if ( deleteFile( $file ) ) { displaySuccess(); } else { displayError(); } }
function deleteFile( $file ) { return (bool) unlink( $file ); }
function displayError() { // pretty error }
and...
function deleteUserInterface( $file ) { deleteFile( $file ); displaySuccess(); }
function deleteFile( $file ) { if ( !unlink( $file ) ) { throw new DeleteError(); } }
class DeleteError extends MWException{ function getHTML() { // pretty error } }
which is better? Should the backend dictate the error format by specifying an exception class with a fixed format? Of course, a caller wishing to override the formatting could catch the exception, but is that better than the old method of using a success/failure return value?
Should error handling be completely exception-dominated? Is there any role for success/failure return values in a language with exception support?
-- Tim Starling
On 6/7/06, Tim Starling t.starling@physics.unimelb.edu.au wrote:
which is better? Should the backend dictate the error format by specifying an exception class with a fixed format? Of course, a caller wishing to override the formatting could catch the exception, but is that better than the old method of using a success/failure return value?
Should error handling be completely exception-dominated? Is there any role for success/failure return values in a language with exception support?
Assuming this is a general question not specifically related to MediaWiki, the general answer is that exceptions should only be used for exceptional circumstances, and likely failures are better off handled with return codes. It's better to use exceptions for weird things like running out of memory, suddenly being unable to access the disk, or an assertion failing, rather than something as banal as a bad filename being supplied, for instance.
Also, it's not usually good practice to allow uncaught exceptions, as in your "pretty error" case, is it?
HTH Steve
Steve Bennett wrote:
On 6/7/06, Tim Starling t.starling@physics.unimelb.edu.au wrote:
which is better? Should the backend dictate the error format by specifying an exception class with a fixed format? Of course, a caller wishing to override the formatting could catch the exception, but is that better than the old method of using a success/failure return value?
Should error handling be completely exception-dominated? Is there any role for success/failure return values in a language with exception support?
Assuming this is a general question not specifically related to MediaWiki, the general answer is that exceptions should only be used for exceptional circumstances, and likely failures are better off handled with return codes. It's better to use exceptions for weird things like running out of memory, suddenly being unable to access the disk, or an assertion failing, rather than something as banal as a bad filename being supplied, for instance.
Do you have some sort of justification for this view?
Also, it's not usually good practice to allow uncaught exceptions, as in your "pretty error" case, is it?
It's not practical to put a try block around every entry point. MediaWiki has quite a lot of entry points. What's more, the exception framework is only initialised part-way through Setup.php, not at compile time as it would be in C++, so it makes sense to install an exception handler to catch exceptions which are thrown between that point and the return to the enclosing scope (e.g. index.php). PHP has a bug with exceptions thrown from within catch blocks, and this means that standard exception handling requires some 10 lines of boilerplate, making a try block on every entry point less practical still. Although it might offend purists, the exception handler works perfectly and transparently in all current cases. All the benefits of using exceptions are still present.
-- Tim Starling
On 6/7/06, Tim Starling t.starling@physics.unimelb.edu.au wrote:
Assuming this is a general question not specifically related to MediaWiki, the general answer is that exceptions should only be used for exceptional circumstances, and likely failures are better off handled with return codes. It's better to use exceptions for weird things like running out of memory, suddenly being unable to access the disk, or an assertion failing, rather than something as banal as a bad filename being supplied, for instance.
Do you have some sort of justification for this view?
Just what I've read.
Steve
Steve Bennett schrieb:
On 6/7/06, Tim Starling t.starling@physics.unimelb.edu.au wrote:
Assuming this is a general question not specifically related to MediaWiki, the general answer is that exceptions should only be used for exceptional circumstances, and likely failures are better off handled with return codes. It's better to use exceptions for weird things like running out of memory, suddenly being unable to access the disk, or an assertion failing, rather than something as banal as a bad filename being supplied, for instance.
Do you have some sort of justification for this view?
Just what I've read.
For C++, I totally ageee with this. It's just the way it's done, and proved to be a viable solution.
I see no reason to stray from this well-established path in PHP. Exceptions are to be used for, well, exceptional events. Bad user input is normal. Hard drive going down is exceptional.
Magnus
On 6/7/06, Magnus Manske magnus.manske@web.de wrote:
For C++, I totally ageee with this. It's just the way it's done, and proved to be a viable solution.
I see no reason to stray from this well-established path in PHP. Exceptions are to be used for, well, exceptional events. Bad user input is normal. Hard drive going down is exceptional.
Fwiw, I was speaking from a Delphi/Java experience, no idea how it relates to PHP, which I've never used.
Steve
On Wed, 07 Jun 2006 16:54:02 +1000, Tim Starling wrote:
Steve Bennett wrote:
On 6/7/06, Tim Starling t.starling@physics.unimelb.edu.au wrote:
which is better? Should the backend dictate the error format by specifying an exception class with a fixed format? Of course, a caller wishing to override the formatting could catch the exception, but is that better than the old method of using a success/failure return value?
If catching the exception to override the formatting would require the additional 10 lines of boilerplate code that you mention below then that seems to be a good argument against using an exception class.
Should error handling be completely exception-dominated? Is there any role for success/failure return values in a language with exception support?
Assuming this is a general question not specifically related to MediaWiki, the general answer is that exceptions should only be used for exceptional circumstances, and likely failures are better off handled with return codes. It's better to use exceptions for weird things like running out of memory, suddenly being unable to access the disk, or an assertion failing, rather than something as banal as a bad filename being supplied, for instance.
Do you have some sort of justification for this view?
I share and have considered that view; here are two justifications:
* consistency. A caller of a routine that needs to access the routine's status shouldn't have to ask itself, "now, do I need to handle an exception, check the return code, or both?"
* clarity. Due to their automatic propagation, exceptions are capable of interrupting the normal flow of code in an unusual way that can make it harder to read, and so should be used sparingly.
A useful policy could be to treat exceptions and their handling as one part of a debugging and quality-control framework (e.g. throwing exceptions on assertion failures as the quoted advice suggests), and to use them only conservatively for other error types. One set of criteria for non-debugging and non-QC use might be that the exceptional circumstance is: * critical but rare and unexpected, and * beyond the direct control of the software, and * a possibility nearly everywhere in the code.
A previous question was:
Should the backend dictate the error format by specifying an exception class with a fixed format?
If consistency of error formatting is to be implemented - and it seems like a good idea to me - then it could be achieved by means other than an exception class. One possibility is an ErrorFormatter class. Another is an advertised and simple protocol for error output based on use of css classes for styling.
[...]
PHP has a bug with exceptions thrown from within catch blocks, and this means that standard exception handling requires some 10 lines of boilerplate, making a try block on every entry point less practical still.
[...]
On 6/6/06, Steve Bennett stevage@gmail.com wrote:
Assuming this is a general question not specifically related to MediaWiki, the general answer is that exceptions should only be used for exceptional circumstances, and likely failures are better off handled with return codes. It's better to use exceptions for weird things like running out of memory, suddenly being unable to access the disk, or an assertion failing, rather than something as banal as a bad filename being supplied, for instance.
In languages where you have hardware-level access and can detect hardware issues, exceptions make sense. For a language such as PHP where you don't have such low-level access and will not run into such issues, the severity threshold for using an exception is lowered, IMO. Personally, I handle errors in PHP using a custom error handler as follows:
If something wrong happens in a function, you call trigger_error() and pass an error message and severity constant. I override PHP's error handler with set_error_handler(). In my custom error handler function, if the error severity is great enough to warrant program termination, I throw an exception. If not, the error simply gets logged or handled in its own way. Basically, I use exceptions to terminate program execution and return types to alter program execution.
Greg
Thanks to everyone for your comments. It seems my own intuition on this more or less agrees with what everyone was saying. The code I committed before this thread took off was more or less going in the right direction, although there are some places where exceptions have been used as a stopgap, and they should probably be migrated to use return values at some stage.
Gregory Szorc wrote:
If something wrong happens in a function, you call trigger_error() and pass an error message and severity constant. I override PHP's error handler with set_error_handler(). In my custom error handler function, if the error severity is great enough to warrant program termination, I throw an exception. If not, the error simply gets logged or handled in its own way. Basically, I use exceptions to terminate program execution and return types to alter program execution.
The basic problem I was facing was that the original MediaWiki code used program termination in patently inappropriate places. The best and most commonly used error page function, OutputPage::errorpage(), exited the program after outputting its text. The task at hand was to remove all of these exit() calls, to support applications such as an HTTP server embedded in MediaWiki. Also, customised handling of unexpected database query errors was desired, and exceptions were the obvious means to do that.
I replaced most of the program terminations in error exits with a return to normal program flow. In certain cases where it looked a bit difficult, I used an exception instead, but that can be fixed at a later date.
For unexpected code branches which appear to be unreachable through ordinary user action, the previous code exited with a backtrace; I replaced these with an exception throw to produce similar behaviour.
For the benefit of extensions and other unmigrated code, the old interfaces such as OutputPage::errorpage() and wfDebugDieBacktrace() simulate the old behaviour by throwing an exception, thus avoiding an unexpected return of control.
-- Tim Starling
I wrote:
Thanks to everyone for your comments. It seems my own intuition on this more or less agrees with what everyone was saying. The code I committed before this thread took off was more or less going in the right direction, although there are some places where exceptions have been used as a stopgap, and they should probably be migrated to use return values at some stage.
Maybe I should add that the reason I was unsure was because of the common practice of standard libraries in languages such as Java to throw exceptions at the drop of a hat, thus forcing the programmer to either inefficiently duplicate validity checks on parameters before calling, or to put try/catch blocks around every damn call.
That's not to say I support PHP's error model unconditionally, where unnecessary warnings encourage programmers to use the incredibly evil @ operator. But at least you can find a substring of a string without having exceptions thrown at you. I guess that's an advantage of weak typing more than anything -- PHP consistently uses specially typed returns to indicate errors.
-- Tim Starling
Should error handling be completely exception-dominated? Is there any role for success/failure return values in a language with exception support?
1) No. 2) Yes.
the general answer is that exceptions should only be used for exceptional circumstances, and likely failures are better off handled with return codes.
I fully agree with that. Don't use exceptions for something you regularly _expect_ to happen in your software like in the example of the first post. The reasons I know are: * You mask the control flow of the application. Some other developer reading your code will easier understand some if-else structure instead of a block of code, where the control flow is dictated indirectly by exception handling. * Exception handling has high runtime costs in most languages (if it actually occurs), as far as I know. But I don't know, if that's also true for PHP. * From personal experience with foreign code I'd say: If exception handling is used very often throughout the code of a project, then people tend to put exception handling around _everything_, even if there is actually no chance to handle the exceptional event in a meaningful way and it would be better to just return an error, to terminate the code or to have some other fallback strategy.
Ciao, Michael.
wikitech-l@lists.wikimedia.org