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?
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.
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.
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.
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.
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
}
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With