2

I have a function in PHP that launches an exception, code after that exception is never executed despite the exception where thrown or not.

if ($a == 1) throw new Exception("Message");
echo "Dose not execute for $a == 0";

I know that when an exception occur code after that won't be reached, but in my example when $a == 0 no exception is thrown but even echo isn't executed.

Well thanks, I hope someone could find out what is going on with my PHP, by the way it is 5.3.

1
  • First thing I would recommend is to always use braces. Commented Oct 14, 2011 at 15:31

3 Answers 3

6

Throwing an exception by definition ends the current run (function, method, etc). If you don't want this behavior, don't throw exceptions.

Also, you don't need to echo out the error after the exception was thrown, just include the error with the exception.

Sign up to request clarification or add additional context in comments.

Comments

2

IF you're assing '0' to '$a' like this, $a == 0, of course it doesn't work, because you're not assigning a value, but checking for equality (not strict);

This code:

$a = 0;
if ($a == 1) throw new Exception("Message");
echo "Dose not execute for $a == 0";

works. I.E., the echo works ("Dose not execute for 0 == 0"), since $a != 1. and no exception is thrown. You should use single quotes to have a message (wrong as it is) like "Dose not execute for $a == 0", since with double quotes the variable is subsitute in the string.

this code:

$a = 1;
if ($a == 1) throw new Exception("Message");
echo "Dose not execute for $a == 0";

throws an exception, which stops the running of the script and the echo doesn't get executed. So, it works.

A code like yours,

$a == 0;
if ($a == 1) throw new Exception("Message");
echo "Dose not execute for $a == 0";

Simply returns an Undefined variable error, since $a is not defined. Most likely, you don't have error enabled/displayed and cannot, as a consequence, see anything.

Comments

0

It could be a problem with your version of PHP or another problem with Apache/Nginx. Use the brackets to make sure what’s going on and make the code clearer. And also use 3 equals because 1 and 0 can be confused with true or false

if ($a === 1) {
  echo "Does NOT execute for $a = 0";
  throw new Exception("Message");      
}
echo "Does execute for $a = 0";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.