I have written a java class where if a method throws an exception, an email is sent, via java mail, with a report to the administrators.
It works – my question is w.r.t elegance – to catch the exception thrown by the main method, the sendEmail() method resides in the catch block of the main method. The sendEmail() method has its own try-catch block.
In effect – it looks like below – is there a more beautiful way of writing this?
try {
foo;
}
catch {
try{
sendEmail();
}
catch {
log(e.message);
}
}
Java can have nested try / catch blocks.
If you’d like, you can move the try / catch sendmail block to another method. When the try / catch blocks are more complex, it will make the code easier to understand.