Let's say I have an interface describing a simple service
public interface AccountService
{
public int getUserId(String userName) throws UserNotFoundException;
//...
}
I've written the UserNotFoundException
exception myself and it is specific to this service. Apart from that, anything else that could go wrong is implementation specific.
If I have a
public class DatabaseAccountService
{
@Override
public int getUserId(String userName) throws UserNotFoundException
{
//some stuff that might throw an SQLException
}
}
The connection could be broken, the table could not exist, etc.
While with a FileAccountService
instead, the file could have permission problems, it could exist but be in an invalid format, etc. Lots of implementation-specific problems could happen in both cases.
The thing is, I can't describe all the possible problems of all the possible implementations into my interface. I need someway to describe "things that went wrong and are implementation-specific". Should I wrap such exceptions into a RuntimeException
or add another exception to my signature like OperationFailedException
?
Wrapping the implementation specific exception into a UserNotFoundException
is not even an option. It would be lying, potentially saying an user does not exists while the file may be just not readable.
The problem I see with the RuntimeException
s is that they might not be caught by the user, maybe leading in an application crash when maybe there was something better to do.
The problem I see with an OperationFailedException
is that it's super generic and doesn't add any information to my methods signatures.
public interface AccountService
{
public int getUserId(String userName) throws UserNotFoundException,
OperationFailedException; //dumb, any method can fail
}
Also, I feel like if adding an OperationFailedException
was the best thing to do, such generic exception wrapping type would exist in the standard library. However, as far as I know, such generic exception does not exist, suggesting any exception should be as specific as possible to help programmers.
Do I have any other option? Which one is the best if I want anyone to except as much from my code as from the Java standard library?