I am only learning Exceptions and error reporting, and I am trying to understand behaviours of try/catch and perhaps other methods that I don't know yet. I have code like this:
function nameless(....) {
if(!$condition) {
throw new Exception('Condition not met');
}
[someCode ...]
return $result;
}
I want to make sure that someCode
only executes if the condition is met. Would a structure like this guarantee that it?
Before talking about putting the rest of the code in an else
block, or other methods, I want to know if there is some way to execute nameless()
in a way that would continue its execution after it throws the exception.
Once I know that, I would like to know if there are better/worse ways of doing things and if this particular example is poor or it's one of a hundred equally valid ways to do this. Thank you.
Yes, it will stop. The behavior is defined here:
When an exception is thrown, code following the statement will not be executed, and PHP will attempt to find the first matching catch block. If an exception is not caught, a PHP Fatal Error will be issued with an "Uncaught Exception ..." message, unless a handler has been defined with set_exception_handler().
Based on the definition and purpose of exceptions, the function should not continue after an exception, and you shouldn't look for a way to force that to happen.
If you have some code that must be executed even after an exception is thrown, you should not include it in the function, but instead enclose the function in a try/catch
, with the necessary code in a finally
block.