...
This noncompliant code example also violates ERR13-J. Do not throw RuntimeException and ERR14-J. Do not catch NullPointerException, RuntimeException, Exception, or Throwable.
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")); } } |
...
This approach is fragile, because any unanticipated checked exception bypasses the dynamic check. See ERR14-J. Do not catch NullPointerException, RuntimeException, Exception, or Throwable for more details.
Compliant Solution (java.lang.reflect.Constructor.newInstance()
)
...