Can I use throws in constructor?

前端 未结 12 2105
迷失自我
迷失自我 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:18

    Generally it is a bad idea to do heavy lifting in constructors: in many languages, you'll be restricted anyhow in what can be done about exceptions during construction.

    0 讨论(0)
  • 2021-01-13 21:20

    You sure can (for example, FileOutputStream does).

    Throwing an exception from the constructor should be done wisely - make sure you clean up after yourself cleanly. Throwing exceptions in a constructor is sometimes done in order to make sure RAII is held.

    0 讨论(0)
  • 2021-01-13 21:20

    I suggest try/catch, and throw usefull errors from your catches. This will give users a better sense of what is going wrong with your application. For example you should check for file existence, and properly formated conditions.

    0 讨论(0)
  • 2021-01-13 21:21

    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.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-13 21:31

    Of course, it's actually used a lot in Java. For example,

    public FileInputStream(String name)
                    throws FileNotFoundException
    
    0 讨论(0)
提交回复
热议问题