Can I use throws in constructor?

前端 未结 12 2129
迷失自我
迷失自我 2021-01-13 21:03

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/

12条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-13 21:39

    In general it is a good idea to have only simple logic in your constructor (for example setting private fields with arguments values). And set up your objects with other special "assemblers", "preparers" or "factories". The same is about get/set methods- they should be as simple as possible.

    Sure it is possible to throw an exception from constuctor. But this is not a good practice.

提交回复
热议问题