Reputation: 1970
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
Reputation: 11
You can use finally
. Code in this branch will be executed even if exception is thrown within catch branch
Upvotes: 0
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
Reputation: 895
You have 2 possible ways:
Upvotes: 1
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