Home » Php » PHP exception inside catch: how to handle it?

PHP exception inside catch: how to handle it?

Posted by: admin July 12, 2020 Leave a comment

Questions:

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?

How to&Answers:

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
   }
}

Answer:

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;
}

Answer:

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.