Sevengames Xoom
Sevengames Xoom

Reputation: 322

Throw new exception doesn't stop the code

I want to stop code execution (all application code). Actually I manage this code:

try
    {
        $connection = mysqli_connect(   $this->_host,
            $this->_username,
            $this->_dbPass,
            $this->_dbName  );

        if(mysqli_connect_errno())
        {
            throw new Exception("problem in connection.");
        }
    }
    catch(Exception $ex)
    {
        header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
        echo json_encode(array("success" => false, "message" => $ex->getMessage()));
        return;   //<- application don't end
        //exit(); //<- application end
     }

Now if I call another method after the above code block that prints "hello world" with the return statement I get the echo, but if I use exit() I don't see any echo. So my question is: throw a new exception don't stop the application instance? I must use exit() for stop it after the exception instead of return?

Upvotes: 0

Views: 3543

Answers (1)

Devon Bessemer
Devon Bessemer

Reputation: 35347

There has been quite a discussion in the comments, but to answer the question at hand, a return does stop execution of the script in the global scope.

http://sandbox.onlinephpfunctions.com/code/59a49286b1cbb62e92fd95134593c2da5ef94468

Example:

<?php

try {
    throw new Exception('Hello');
}
catch (Exception $e) {
    return;
}
echo "hello world"; // Not reached

?>

An exception will stop execution if it is uncaught. Otherwise, if the exception is caught, the same rules apply. In the global scope, return will exit the application, inside a function or method, a return will only exit the function.

exit() or die() will both exit the application no matter what scope they are called in.

Upvotes: 4

Related Questions