I have this factory method in java:
public static Properties getConfigFactory() throws ClassNotFoundException, IOException {
if (config == null) {
Two points regarding exception handling best practices:
And you may throw the RuntimeException with or without inner exception, depending on what the caller can do with it. If you're not rethrowing the inner exception then you should log it in your method, if important.
A RuntimeException
should be used only when the client cannot recover from whatever the problem is. It is occasionally appropriate to do what you are talking about, but more often it is not appropriate.
If you are using a JDK >= 1.4, then you can do something like:
try { // Code that might throw an exception } catch (IOException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); }
and the rethrown RuntimeException
will have the original cause included inside it. This way, someone at the top of the thread catching the RuntimeException
-- your threads do catch RuntimeException
so they don't just silently die, right? -- can at least print out the FULL stack trace of the cause.
But as others have said and will say, exceptions are checked for a reason. Only do this when you are positive that your clients cannot recover from the problem that you are rethrowing as an unchecked exception.
NOTE: Better than just RuntimeException
would be to use a more specific unchecked exception if one is available. For example, if the only reason your method could throw a ClassNotFoundException
is because a configuration file is missing, you could rethrow a MissingResourceException
, which is an unchecked exception but gives more information about why you are throwing it. Other good RuntimeException
s to use if they describe the problem you are rethrowing are IllegalStateException
, TypeNotPresentException
and UnsupportedOperationException
.
Also note that it is ALWAYS a good idea for your threads to catch RuntimeException and at a minimum log it. At least this way you understand why your threads are going away.
You are doing it the correct way.
In order to let checked exceptions pass though without being checked, you must wrap them in un-checked exceptions.
Just remember, Exceptions are checked for a reason.
If you want to avoid too many try - catch
es, catch both the exceptions in the factory itself and handle them there.
Perhaps return a default implementation.
You have to handle the exceptions, here or somewhere else.
And since this is a factory, I think it is better that these exceptions are handled in the factory itself (same method or different method), and returning a default implementation.
Anyway, the (business function) caller will have no clue on what has to be done when it encounters a ClassNotFoundException
.