...
Catching and suppressing exceptions is considered bad practice for several reasons. Exceptions disrupt the expected control flow of the application. For example, statements that occur in the try
block after the statement that caused the exception, do not execute as required.
To ensure that the program does not resume with invalid invariants, the catch
block should immediately stop control flow from proceeding, instead of ignoring or suppressing the exception. If the program is capable of recovering from the exceptional condition, the statements in the try
block that are required to be executed, must be moved outside the try
block.
...
Note that even though the application reacts to the exception by printing out a stack trace, it proceeds as if the exception was not thrown, that is, the future long term behavior of the application does not change based on the throwing of the exception, other than the fact that impending statements in the try block are skipped. Given that the resulting IOException
indicates that an operation attempted by the application failed, it is unlikely that the application will be able to operate successfully by assuming that the attempted operation succeeded.
...
This compliant solution attempts to recover from a FileNotFoundException
by forcing the user to specify another file when a particular file does not exist in the user-specific directory.
Code Block | ||
---|---|---|
| ||
boolean volatile validFlag = false; do { try { // If requested file does not exist, throws FileNotFoundException // If requested file exists, sets a Boolean flag validFlag to true validFlag = true; } catch(FileNotFoundException e) { // Ask the user for a different filename } } while(validFlag != true); // Use the file |
...
Code Block | ||
---|---|---|
| ||
try {
// Requested file does not exist
// User is unable to supply the file name
} catch(FileNotFoundException e) {
throw new RuntimeException(e);
}
|
...