PHP exception inside catch: how to handle this?

Suppose you have PHP code inside a try...catch . Suppose that inside the catch you would like to do something (i.e. send an email) that could 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 a catch ?

+6
source share
3 answers

You should not throw anything into catch . If you do, you can drop this inner layer of try-catch and catch exceptions into the outer layer of try-catch and handle this exception.

eg:

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

can be replaced by

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

Based on this answer , it seems perfectly right to nest try / catch blocks, for example:

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

You have 2 possible ways:

  • You exit the program (if this is serious), and you write it to the log file and inform the user.
  • If the error is related to your current class / function, you throw another error inside the catch block.
0
source

Source: https://habr.com/ru/post/974368/


All Articles