I have a question regarding exception handling and resource management, and I was wondering if anyone could share their opinion. I need to perform a sequence of actions: read the application settings, configure the environment, make the material, and then clear it. Cleaning involves tearing down the environment, but this should only happen if it has been successfully configured in the first place.
Here is my first (and lame) approach:
try {
readSettings();
setupEnvironment();
} catch (Exception ex) {
logStackTrace(ex);
displayError(ex);
closeCommThreads();
return;
}
try {
} catch (Exception ex) {
logStackTrace(ex);
displayError(ex);
} finally {
teardownEnvironment();
closeCommThreads();
}
It seemed a little ugly, so I decided to look for a better solution. I did some reading, and quite a few articles voted for large blocks try/catchand using (pun finallyintended ?) To clean up. So here is my second attempt:
try {
readSettings();
setupEnvironment();
} catch (Exception ex) {
logStackTrace(ex);
displayError(ex);
} finally {
teardownEnvironment();
closeCommThreads();
}
, teardownEnvironment(), - setupEnvironment() ( : - ?). ? , .
Edit:
, : , teardownEnvironment - - if (!isSetup()) return;.