sanjihan
sanjihan

Reputation: 5992

Prevent PHP from echoing if exception occured

I noticed that PHP's echo successfully prints strings even if somewhere in the script an error is thrown and not handled. For example:

error_reporting(E_ALL);
ini_set('display_errors', 1);

echo "started";
throw new Exception("big error");
echo "done";

prints "started", even though an error occured. The status code is 500 indeed, but I don't think displaying partial results works for all cases.

Using ob_start() and ob_get_contents() offers some flexibility, but I expected that PHP offers a switch to set displaying to none if error occured. Does this switch exist?

Upvotes: 0

Views: 546

Answers (4)

Martijn
Martijn

Reputation: 16103

Echo instantly send the data to the server (at least in this code it does) and no longer can be affected by what happens next. It's generally bad practice to work like that (eg: after an echo you can no longer change headers like a redirect, which can be very inconfinient), better would be to stored everything in a variable and output it when you want:

$output = "started";
throw new Exception("big error");
$output.= "done";

echo $output; // or if in a function, return instead of echo

Upvotes: 1

Francesco Manicardi
Francesco Manicardi

Reputation: 809

One way to solve this would be using a variable to store what you want to echo and only echo it if there are no uncaught exceptions

$echoStr = "";

$echoStr .="started";

throw new Exception("big error");
$echoStr .="done";

echo $echoStr;

Upvotes: 1

Chemaclass
Chemaclass

Reputation: 2011

echo "started"; // <- This will occurs
throw new Exception("big error"); // <- And here the Exception will be thrown
echo "done"; // <- therefore, this line won't be reached

Upvotes: 2

Shiva
Shiva

Reputation: 88

when you say throw new Exception() this means you are saying move the program control to caller and don't execute the further statements after this throw statement.

thanks to: Difference between "throw new Exception" and "new Exception"?

Upvotes: 2

Related Questions