...
The following noncompliant code example attempts to work around the fact that Class.newInstance()
can throw undeclared checked exceptions. It catches Exception
and dynamically checks whether the caught exception is an instance of the possible checked exception (carefully re-throwing all other exceptions, of course), as shown below. This approach is fragile, because any unanticipated checked exception bypasses the dynamic check. See ERR14-J. Do not catch RuntimeException for more details.
Code Block | ||
---|---|---|
| ||
public static void main(String[] args) { try { NewInstance.undeclaredThrow(new IOException("Any checked exception")); } catch(Exception e) { if (e instanceof IOException) { System.out.println("IOException occurred"); } else if (e instanceof RuntimeException) { throw (RuntimeException) e; } else { //some other unknown checked exception } } } |
...