Programmers often fall into the trap of suppressing or ignoring checked exceptions. Unless there is a valid reason for ignoring exceptions, such as the client cannot be expected to stage a recovery, it is important to handle them appropriately. The thrown exception disrupts the expected control flow of the application and care must be taken to not assume that the expected control flow has happened after catching an exception. The implication of not ignoring an exception is that the application does not assume normal control flow occurred after catching an exception and the application bases its future long term behavior on the fact that the exception was thrown. ensure that all statements in the try
block, before the catch
block execute as expected. Failure to take the actual system state into account after when the throwing of an exception is caught may result in security problems as if the application continues to execute as if nothing has happened.
Noncompliant Code Example
In this This noncompliant code example , the programmer leaves adorns the catch
block adorned with an ignore comment.
Code Block | ||
---|---|---|
| ||
try { //... } catch(IOException ioe) { /* ignore *// Ignore } |
Noncompliant Code Example
Printing the exception's stack trace can be useful for debugging purposes but is equivalent to ignoring the exception, as this noncompliant code example demonstrates.
...
Code Block | ||
---|---|---|
| ||
try { // Requested file does not exist } catch(FileNotFoundException e) { /*/ askAsk the user for a different filename */ } |
Exceptions
EX1: It is reasonable to ignore handling an exception that occurs within a catch
or finally
block, such as when closing a FileInputStream
object.
...
Code Block | ||
---|---|---|
| ||
// whenWhen recovery is possible at higher levels private void doSomething() throws FileNotFoundException { // Requested file does not exist; throws FileNotFoundException // Higher level code can handle it by displaying a dialog box and asking // the user for the file name } |
...