I have a problem with methods from a Data class : public String read(int recNo) throws RecordNotFoundException;
public void update(int recNo, String data, long lockCookie) throws RecordNotFoundException, SecurityException;
public void delete(int recNo, long lockCookie) throws RecordNotFoundException, SecurityException;
public int find(String criteria);
public int create(String data) throws DuplicateKeyException;
public long lock(int recNo) throws RecordNotFoundException;
public void unlock(int recNo, long cookie) throws RecordNotFoundException, SecurityException;.
They can throw only specified exception. What should I do with caught exceptions inside this methods(which are in throws declaration)? For example create method can throw only DuplicateKeyException, but inside it can appear IOException. Throwing a DuplicateKeyException is ridiculous and I can�t do nothing (leave empty catch). Do you have any idea what to do? Please help me.
Hum... I did not run into these problems, since I open the .db file when the application starts and put all records in a HashMap, so when creating a record, there's no risk to run into an IOException. Yes, throwing a DuplicateKeyException in these cases would be wrong (or not that right), but in your case, what you can do is throw unchecked exceptions, like RuntimeException. In many cases, I throw IllegalArgumentExceptions or IllegalStateExceptions.
I considered to use what is given by DB interface. So if inside the update, read, delete or lock method would be caught an IOException the method will throw RecordNotFoundException which is available. If IOException is caught in the find method empty int array is returned. If IOException is caught in the create method -1 value is returned.
Do you think is it a good solution? I have doubts especially about returning -1 value which can be considered as bad programming practice.
What I implemented and what I think is the best to do in this situation - throw your own unchecked exceptions. They don't modify the DB interface, so it should be safe.
Edit: Oh, and you should not throw RuntimeException directly, but use a subclass of it. For IOException, maybe IllegalStateException is also suitable, but not IllegalArgumentException. Or, even better I think, you should create your own unchecked exceptions. [ December 17, 2008: Message edited by: Alecsandru Cocarla ]
For me, wrapping IOException in RecordNotFoundException is not "nice".
Agreed. An IOException is not a RecordNotFoundException. In your case, I really think the best option is to throw a RuntimeException, or a subclass of it. For instance, in my create method, if I don't get a String array of 7 positions properly filled (I only allowed the custumer ID to be null), I throw an IllegalArgumentException. They exist, let's use them!