Why OSGI BundleActivator methods are declared with “throws Exception”?
Domanda
Both start
and stop
methods of OSGI BundleActivator are declared with throws Exception
. At the same time in his book Effective Java, Second Edition, Item 62, Joshua Bloch says
never declare a method "throws Exception"
So is it a poor design decision in BundleActivator
or such generality is justified in this case and why?
Soluzione
Please note, that you can declare your start
and stop
methods without any throws
clause. (Or you can declare these methods with any java.lang.Exception
subclasses.)
On the other hand, a specific, for example
void start(BundleContext context) throws BundleActivatorException
method would not change too much. It would just made implementers to catch their exceptions and rethrow it wrapped inside a BundleActivatorException
. Since every exception makes bundle activation pointless this try-catch
block is really unnecessary, so it's easier to throw java.lang.Exception
.
Altri suggerimenti
Throwing an exception from a start()
or stop()
method indicates that something is seriously wrong, and the bundle lifecycle change should not go through. Since we separate the concerns of detecting the situation (by the bundle), and handling it (by the framework), throwing Exception
is the only reasonable thing to do.
I consider Josh Bloch's advice anachronistic. There is nothing wrong with throws Exception
. It gives you the option to throw whatever exception you like, and the OSGi framework will handle it.
Note that you never need to invoke these methods yourself.