Sun appararently did this to allow checked exceptions to be thrown directly from Class.newInstance()
, rather then either being wrapped in InvocationTargetException or having throws Exception
declared on the signature.
This is an "interesting" design decision as it differs from patterns elsewhere -- Constructor.newInstance() for example will wrap any constructor exceptions in an InvocationTargetException.
The "benefit" it supposedly provides is:
the ability to catch constructor exceptions directly, at their original type; and
avoids newInstance() needing to declare throws Exception
and the caller to catch Exception.
The downside is:
- the checked exceptions are not declared. This obviates the main advantage/ purpose of checked exceptions, and may produce warnings that the catch block is unreachable due to the checked exception not being declared.
Would this be a pattern you might use in your code? To me this seems fairly unlikely. It seems mostly potentially applicable to generic/ framework code, where client code being wrapped by the framework potentially throws checked exceptions. Then it would only be desirable to use, if you wished to propagate checked exceptions out without declaring they can be thrown.. For me this is questionable.
Most Java framework methods wrapping client code, are designed in one of three exception paradigms:
- purely runtime exceptions, or
- declaring
throws Exception
to allow the full gamut of checked exceptions, or
- the 'rethrow in a wrapper' approach (consider using an unchecked exception as the wrapper, though).
This particular Class.newInstance
method is very unusual, and by not declaring the checked exceptions which can potentially be thrown it bypasses/ obviates the only real benefit of checked exceptions.
Generally, there has been a major shift towards runtime rather than checked exceptions, and I would not recommend Unsafe.throwException()
(nor the "generics hack" mentioned by Lukas above.)
For application code, I would recommend to use runtime exceptions if possible & declare the exception types thrown. For framework code, consider the three paradigms above with a preference towards runtime exceptions.
Background: http://literatejava.com/exceptions/checked-exceptions-javas-biggest-mistake/