?

Log in

May. 14th, 2008 @ 11:49 am Alternative to die/exit
EDIT: SOLVED.  Using PHP5 exceptions, as follows:

echo "Before function call\n";

try {
    first();
} catch (Exception $fatalErrorInCoreConversion) {
    echo 'Caught exception: ',  $fatalErrorInCoreConversion->getMessage(), "\n";
}

echo "After function call\n";

function first() {
    echo "-In first, before second\n";
    second();
    echo "-In first, after second\n";
}

function second() {
    echo "--In second before the end\n";
    throw new Exception('Aaaaargh.');
    echo "--In second after the end\n";
}


Renders:
Before function call
-In first, before second
--In second before the end
Caught exception: Aaaaargh.
After function call
ORIGINAL QUESTION:
Hi all,

I was wondering what methods you folks use to avoid using die/exit. They keep code simple, but also are clunky on the UI side. OTOH, in a function library, anything other than die could get quite clunky in the code. Consider this code (Example 1):


echo "Before function call\n";
first();
echo "After function call\n";

function first() {
echo "-In first, before second\n";
second();
echo "-In first, after second\n";
}

function second() {
echo "--In second before the end\n";
die("Aargh!");
echo "--In second after the end\n";
}


Which of course renders:

Before function call
-In first, before second
--In second before the end
Aargh!


----
Example 2. If I don't want die, then I need:

echo "Before function call\n";
echo first();
echo "After function call\n";

function first() {
echo "-In first, before second\n";
if (second() == "Aargh!") {
return "Croak!";
}
echo "-In first, after second\n";
}

function second() {
echo "--In second before the end\n";
return "Aargh!";
echo "--In second after the end\n";
}


Which renders:

Before function call
-In first, before second
--In second before the end
Croak!
After function call


----
Now, what I want is the behavior of the second example, but the simplicity of code of the first example - i.e. without all the return commands and result checks. So the first example, with die replaced by some magical command or trick, or at least simpler than example two. While it is easy in example 2, imagine an example where I have a function called seventh and therefore have 7 returns and 6 result checks. Ugly code v.s ugly functionality. Any suggestions? Tricks? Hacks? And this is legacy PHP, so framework solutions are a whole other issue. I feel like I'm forgetting something simple.

Further, though it does not help me in the above issue (I believe), do any of you use trigger_error and set_error_handler? Other ways of handling errors?

Thanks,
Grant
About this Entry
Silly - Dirty Face
thirdworld: