DoOrDie

Last edit April 24, 2012
A programming idiom, common in PerlLanguage, CeeLanguage, and other Unix scripting languages (BourneShell, CeeShell) used for error handling.

The idiom is essentially to write code such as the following:

 take_some_action() || handle_the_error();

In PerlLanguage, the way errors are often handled is to throw an exception using Perl's die command, hence DoOrDie. In PHP, the code looks like this:

 DoSomething() or die("Something failed");

This relies on two things:

  • In the languages in question, it is common for a function to return a boolean true value on success, false on failure. (Unix convention is for spawned processes to do the opposite; one uses exit(0) to signify success and exit(1) to signify failure. Unix shells therefore invert the return value to get the true/false value for the shell to evaluate).

  • The boolean OR operator has short circuit semantics.

If the operation succeeds (returns true), then the result of the OR is true and the handle_the_error() code is not executed. If the operation fails, then the handle_the_error() code is executed. Note that usually with DoOrDie the result of the boolean OR operator is not of interest; only its side-effects.

One can do similar stuff with boolean AND to chain operations, ensuring that subsequent operations are only run if their predecessor succeeded.
I'm not normally against exceptions, but in Perl's case the primitive implementation really kills the utility. Making a %SIG{__DIE__} handler useful can be quite a pain. -PA
Why can't you use eval {}?

Perl 5's eval {...};if ($@) {...} is other languages try's equivalent

- Pawel Murias
Topic not to be confused with LimpVersusDie.
CategoryIdiom, CategoryException