I have to initialize file objects inside the constructor and for handling the exception, is it efficient using throws
or should I go for try
/catch
?
It's okay to throw an exception in the constructor. I know some of the Java library classes do so (URI for just one example). I think it's better to throw an exception than to return an object in an unknown or invalid state.
Of course you can and throwing an exception is actually what I would do (instead of swallowing it in the constructor). You want to let the caller know that something unexpected happened, you don't want to return a non properly initialized instance. That said, it may be a sign that you are doing too much things in the constructor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With