Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use throws in constructor?

Tags:

java

exception

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?

like image 350
i2ijeya Avatar asked Nov 27 '22 00:11

i2ijeya


2 Answers

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.

like image 199
Bill the Lizard Avatar answered Dec 17 '22 01:12

Bill the Lizard


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.

like image 45
Pascal Thivent Avatar answered Dec 17 '22 03:12

Pascal Thivent