Java requires that each method must address every checked exception that can be thrown during its execution either by handling the exception within a try-catch
block or by declaring that the exception can propagate out of the method (via the throws
clause). Unfortunately, there are a few techniques that permit undeclared checked exceptions to be thrown at runtime. Such techniques foil the ability of caller methods to use the throws
clause to determine the complete set of checked exceptions that could propagate from an invoked method. Consequently such techniques must not be used to throw undeclared checked exceptions.
Noncompliant Code Example (java.lang.reflect.Class.newInstance()
)
Any checked exception thrown by the default constructor of Class.newInstance()
is propagated to the caller, even though Class.newInstance()
declares that it throws only InstantiationException
and IllegalAccessException
. This noncompliant code example demonstrates one way to use Class.newInstance()
to throw arbitrary checked and unchecked exceptions.
...
Code Block | ||
---|---|---|
| ||
public class NewInstance { private static Throwable throwable; private NewInstance() throws Throwable { throw throwable; } public static synchronized void undeclaredThrow(Throwable throwable) { // These exceptions should not be passed if (throwable instanceof IllegalAccessException || throwable instanceof InstantiationException) { throw new IllegalArgumentException(); // Unchecked, no declaration required } NewInstance.throwable = throwable; try { // next line throws the Throwable argument passed in above, // even though the throws clause of class.newInstance fails // to declare that this may happen NewInstance.class.newInstance(); } catch (InstantiationException e) { /* unreachable */ } catch (IllegalAccessException e) { /* unreachable */ } finally { // Avoid memory leak NewInstance.throwable = null; } } } public class UndeclaredException { public static void main(String[] args) { // No declared checked exceptions NewInstance.undeclaredThrow(new Exception("Any checked exception")); } } |
Noncompliant Code Example (Class.newInstance()
Workarounds)
When the programmer wishes to catch and handle the possible undeclared checked exceptions, the compiler refuses to believe that any can be thrown in the particular context.
...
Code Block | ||
---|---|---|
| ||
public static void main(String[] args) { try { NewInstance.undeclaredThrow(new IOException("Any checked exception")); } catch (Throwable e) { if (e instanceof IOException) { System.out.println("IOException occurred"); } else if (e instanceof RuntimeException) { throw (RuntimeException) e; } else { // forward to handler } } } |
Compliant Solution (java.lang.reflect.Constructor.newInstance()
)
This compliant solution uses Constructor.newInstance()
rather than Class.newInstance()
. The Constructor.newInstance()
method wraps any exceptions thrown from within the constructor into a checked exception called InvocationTargetException
.
Code Block | ||
---|---|---|
| ||
public static synchronized void undeclaredThrow(Throwable throwable) { // These exceptions should not be passed if (throwable instanceof IllegalAccessException || throwable instanceof InstantiationException || throwable instanceof NoSuchMethodException || throwable instanceof InvocationTargetException) { throw new IllegalArgumentException(); // Unchecked, no declaration required } NewInstance.throwable = throwable; try { Constructor constructor = NewInstance.class.getConstructor( new Class<?>[0] ); constructor.newInstance(); } catch (InstantiationException e) { /* unreachable */ } catch (NoSuchMethodException e) { /* unreachable */ } catch (IllegalAccessException e) { /* unreachable */ } catch (InvocationTargetException e) { System.out.println("Exception thrown: " + e.getCause().toString()); } finally { // Avoid memory leak NewInstance.throwable = null; } } |
Noncompliant Code Example (sun.misc.Unsafe
)
This noncompliant code example is insecure both because it can throw undeclared checked exceptions and also because it uses the sun.misc.Unsafe
class. All sun.*
classes are unsupported and undocumented because their use can cause portability and backward compatibility issues.
...
Code Block | ||
---|---|---|
| ||
import java.io.IOException; import java.lang.reflect.Field; import sun.misc.Unsafe; public class UnsafeCode { public static void main(String[] args) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { Field f = Unsafe.class.getDeclaredField("theUnsafe"); f.setAccessible(true); Unsafe u = (Unsafe) f.get(null); u.throwException(new IOException("No need to declare this checked exception")); } } |
Noncompliant Code Example (Generic Exception)
An unchecked cast of a generic type with parametrized exception declaration can also result in unexpected checked exceptions. Any attempt to do so is diagnosed by the compiler, unless the warnings are suppressed.
Code Block | ||
---|---|---|
| ||
interface Thr<EXC extends Exception> { void fn() throws EXC; } public class UndeclaredGen { static void undeclaredThrow() throws RuntimeException { @SuppressWarnings("unchecked") // Suppresses warnings Thr<RuntimeException> thr = (Thr<RuntimeException>)(Thr) new Thr<IOException>() { public void fn() throws IOException { throw new IOException(); } }; thr.fn(); } public static void main(String[] args) { undeclaredThrow(); } } |
Noncompliant Code Example (Thread.stop()
)
Wiki Markup |
---|
According to the Java API \[[API 2006|AA. Bibliography#API 06]\], class {{Thread}}: |
...
Note that Thread.stop()
is deprecated, so this code also violates MET02-J. Do not use deprecated or obsolete classes or methods.
Noncompliant Code Example (Bytecode Manipulation)
Wiki Markup |
---|
It is also possible to disassemble a class, remove any declared checked exceptions, and reassemble the class so that checked exceptions are thrown at runtime when the class is used \[[Roubtsov 2003|AA. Bibliography#Roubtsov 03]\]. Compiling against a class that declares the checked exception and supplying at runtime a class that lacks the declaration also suffices. Similarly, a compiler other than {{javac}} might handle checked exceptions differently. Undeclared checked exceptions can also be produced through crafted use of the {{sun.corba.Bridge}} class. All these methods are strongly discouraged. |
Risk Assessment
Failure to document undeclared checked exceptions can result in checked exceptions that the caller is unprepared to handle, consequently violating the safety property.
Recommendation | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
ERR10-J | low | unlikely | high | P1 | L3 |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="163667f69c421fcf-fc9cef67-45fb4075-856bac6d-3a9d644aab2e95da983bbcab"><ac:plain-text-body><![CDATA[ | [[MITRE 2009 | AA. Bibliography#MITRE 09]] | [CWE-703 | http://cwe.mitre.org/data/definitions/703.html] "Improper Check or Handling of Exceptional Conditions" | ]]></ac:plain-text-body></ac:structured-macro> |
| CWE-248 "Uncaught Exception" |
Bibliography
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="37237f7ec6537639-3b9e151a-418e45c8-9a09adb9-3da619974a5601d794d61dc3"><ac:plain-text-body><![CDATA[ | [[Bloch 2008 | AA. Bibliography#Bloch 08]] | Item 2: "Consider a builder when faced with many constructor parameters" | ]]></ac:plain-text-body></ac:structured-macro> |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="837e872aeeb60147-337b5fb7-4cd34e85-b8aab1ef-5a2ad1e6dc9e5583b2d2725d"><ac:plain-text-body><![CDATA[ | [[Goetz 2004b | AA. Bibliography#Goetz 04b]] |
| ]]></ac:plain-text-body></ac:structured-macro> |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="3cf900e5f1d0a383-b0d72757-4ac84138-88a9bd56-7189f80bd47d8a5d2c02b2be"><ac:plain-text-body><![CDATA[ | [[JLS 2005 | AA. Bibliography#JLS 05]] | Chapter 11: Exceptions | ]]></ac:plain-text-body></ac:structured-macro> |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="6fa4e570c61f1148-5aa8e424-4e3e4659-9815aa3f-6ce73c2b8a6abd9e467fcd3c"><ac:plain-text-body><![CDATA[ | [[Roubtsov 2003 | AA. Bibliography#Roubtsov 03]] |
| ]]></ac:plain-text-body></ac:structured-macro> |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="c2b9a026b029fe61-db93b0c8-4e3a49b3-96e1b87b-675559ac297137e2a549811a"><ac:plain-text-body><![CDATA[ | [[Schwarz 2004 | AA. Bibliography#Schwarz 04]] |
| ]]></ac:plain-text-body></ac:structured-macro> |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="205e528dd1bec17b-00d3e754-48ae4a94-b89899d7-84b3375c6cdd062853483299"><ac:plain-text-body><![CDATA[ | [[Venners 2003 | AA. Bibliography#Venners 03]] | "Scalability of Checked Exceptions" | ]]></ac:plain-text-body></ac:structured-macro> |
...