Can I use throws in constructor?

2020-03-24 06:27发布

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?

12条回答
smile是对你的礼貌
2楼-- · 2020-03-24 07:05

You are supposed to take the object to a safe state in the constructor, but let's imagine you want to open a file(for reading) that doesn't exists, throwing the exception is the only way. So it depends on the logic you implement

查看更多
可以哭但决不认输i
3楼-- · 2020-03-24 07:08

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.

查看更多
唯我独甜
4楼-- · 2020-03-24 07:08

I'd go with 'throws' if you care about what is initialized in the constructor, which I guess you do.

If you hide the exceptions, then that will probably cause problems later on.

查看更多
迷人小祖宗
5楼-- · 2020-03-24 07:08

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

public FileInputStream(String name)
                throws FileNotFoundException
查看更多
smile是对你的礼貌
6楼-- · 2020-03-24 07:11

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.

查看更多
淡お忘
7楼-- · 2020-03-24 07:16

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.

查看更多
登录 后发表回答