...
The user is allowed to access files in only the user-specific directory so no file system information is leaked in the process (EXC06-J. Do not allow exceptions to transmit sensitive information).
Noncompliant Code Example
It is not possible to propagate a checked exception by throwing it from a Runnable
object's run()
method. Consequently, this noncompliant code example catches java.lang.InterruptedException
but ignores it.
Code Block |
---|
|
class Foo implements Runnable {
public void run() {
try {
Thread.sleep(1000);
} catch(InterruptedException e) {
// Ignore
}
}
}
|
Wiki Markup |
---|
Any callers higher up in the call stack are unable to determine that an interrupted exception occurred and act on it \[[Goetz 06|AA. Java References#Goetz 06]\]. |
Compliant Solution
This compliant solution catches the InterruptedException
and restores the interrupted status by calling the interrupt()
method on the current thread.
Code Block |
---|
|
class Foo implements Runnable {
public void run() {
try {
Thread.sleep(1000);
} catch(InterruptedException e) {
Thread.currentThread().interrupt(); // Reset interrupted status
}
}
}
|
Wiki Markup |
---|
Consequently, code that is higher up on the call stack can see that an interrupt was issued \[[Goetz 06|AA. Java References#Goetz 06]\]. |
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 |
---|
|
try {
// Requested file does not exist
// User is unable to supply the file name
} catch(FileNotFoundException e) {
throw new RuntimeException(e);
}
|
Wiki Markup |
---|
*EX3:* "The only situation in which it is acceptable to swallow an interrupt is when you are extending Thread and therefore control all the code higher up on the call stack." \[[Goetz 06|AA. Java References#Goetz 06]\]. In such cases {{InterruptedException}} may be caught and ignored. |
Risk Assessment
Ignoring or suppressing exceptions violates the fail-safe criteria of an application.
...
Wiki Markup |
---|
\[[JLS 05|AA. Java References#JLS 05]\] [Chapter 11, Exceptions|http://java.sun.com/docs/books/jls/third_edition/html/exceptions.html]
\[[Bloch 08|AA. Java References#Bloch 08]\] Item 65: "Don't ignore exceptions", Item 62: "Document all exceptions thrown by each method"
\[[Goetz 06|AA. Java References#Goetz 06]\] 5.4 Blocking and interruptible methods
\[[MITRE 09|AA. Java References#MITRE 09]\] [CWE ID 390|http://cwe.mitre.org/data/definitions/390.html] "Detection of Error Condition Without Action" |
...