Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 453
Giorgio Avatar asked Aug 26 '14 12:08

Giorgio


People also ask

How do you handle catching exception?

The first catch block that handles the exception class or one of its superclasses will be executed. So, make sure to catch the most specific class first. If an exception occurs in the try block, the exception is thrown to the first catch block. If not, the Java exception passes down to the second catch statement.

How can you handle the exception in PHP?

The primary method of handling exceptions in PHP is the try-catch. In a nutshell, the try-catch is a code block that can be used to deal with thrown exceptions without interrupting program execution. In other words, you can "try" to execute a block of code, and "catch" any PHP exceptions that are thrown.

Can you nest try-catch blocks PHP?

Try-catch blocks in PHP can be nested up to any desired levels and are handled in reverse order of appearance i.e. innermost exceptions are handled first.

How do you stop the execution after try-catch?

You can throw the exception after catching it speakTo* methods. This will stop execution of code in methods calling speakTo* and their catch block will be executed. Save this answer.


2 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
   }
}
like image 162
Simon East Avatar answered Oct 12 '22 23:10

Simon East


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;
}
like image 32
Justinas Avatar answered Oct 13 '22 00:10

Justinas