Giorgio
Giorgio

Reputation: 1970

PHP exception inside catch: how to handle it?

Suppose to have a PHP code inside a try...catch block. Suppose that inside catch you would like to do something (i.e. sending email) that could potentially fail and throw a new exception.

try {
    // something bad happens
    throw new Exception('Exception 1');
}
catch(Exception $e) {
    // something bad happens also here
    throw new Exception('Exception 2');
}

What is the correct (best) way to handle exceptions inside catch block?

Upvotes: 13

Views: 11293

Answers (4)

Vasiliy Aristov
Vasiliy Aristov

Reputation: 11

You can use finally. Code in this branch will be executed even if exception is thrown within catch branch

Upvotes: 0

Simon E.
Simon E.

Reputation: 58460

Based on this answer, it seems to be perfectly valid to nest try/catch blocks, like this:

try {
   // Dangerous operation
} catch (Exception $e) {
   try {
      // Send notification email of failure
   } catch (Exception $e) {
      // Ouch, email failed too
   }
}

Upvotes: 11

sridesmet
sridesmet

Reputation: 895

You have 2 possible ways:

  1. You exit the program (if it is severe) and you write it to a log file and inform the user.
  2. If the error is specifically from your current class/function, you throw another error, inside the catch block.

Upvotes: 1

Justinas
Justinas

Reputation: 43441

You should not throw anything in catch. If you do so, than you can omit this inner layer of try-catch and catch exception in outer layer of try-catch and process that exception there.

for example:

try {
    function(){
        try {
            function(){
                try {
                    function (){}
                } catch {
                    throw new Exception("newInner");
                }
            }
        } catch {
            throw new Exception("new");
        }
    }
} catch (Exception $e) {
    echo $e;
}

can be replaced to

try {
    function(){
        function(){
            function (){
                throw new Exception("newInner");
            }
        }
    }
} catch (Exception $e) {
    echo $e;
}

Upvotes: 1

Related Questions