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
?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
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
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.
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.
Of course, it's actually used a lot in Java. For example,
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.
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.