Can I use throws in constructor?

前端 未结 12 2229
迷失自我
迷失自我 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条回答
  •  南方客
    南方客 (楼主)
    2021-01-13 21:24

    To me, that's not a question of efficiency.

    If you can react on the exceptional state and still create a valid or at least useable object, then handle it within the constructor.

    Otherwise - in case the object is not usable - throw the exception back at the caller. In that case, he won't get an object and can't continue with an unusable/inconsistant instance which might produce errors in some other corners of the application.

提交回复
热议问题