Ziyao Wei Ziyao Wei - 1 year ago 51
Java Question

Java: Should I / What to throw when authentication is excepted?

I am writing a small library, and in which I need to access several different type of files. While the access method itself is different for each kind of file format, they seem to have a lot in common, and I put an interface in the class hierarchy, in which I wrote a method that should connect to the data source.

However, since the data source might be protected by password and/or user permission, sometimes it need authentication to retrieve the data. My questions are:


  1. It is a good idea to throw an exception when authentication is required?

    Since I want to expose the implementation as little as possible, I only want to tell the user what happened. But authentication might need many different things (username, password, etc.), so could I pack them into one exception and throw it out? Or, maybe there is a better way without resorting to exceptions, since "Authentication required" is not really the exceptional behavior that exception usually used to handle.

  2. What exception to throw when authentication is required?

    Now suppose I decided to use exception to handle this. Which exception should I throw? The several
    AuthenticationException
    s shipped with Java API does not seem to fit this requirement since they all seem to be very case specific, e.g., used in the naming service. I am not sure if
    SecurityException
    is the way to go, but if this is improper, I still really do not want to throw my own exception, since that will impede other people to understand my code and what is going on behind the API.



Thanks for any input! This is somewhat lengthy or maybe too verbose, so any edits that would improve the question is extremely welcomed.

Answer Source

Since it's your own API, you might create your own Exception to go with it, which can carry the details... There's no requirement or benefit to using the Java exception that "sounds closest to" your exception.

I personally find that peppering my code with try/catch blocks is... tedious and unsightly. So I try to make API's that don't require it.

In your case, maybe you could provide queries so your API clients could preflight the actions, and their usage might look something like:

Thing t = new Thing(...);
if(t.needsAuth())
{
  boolean ok = t.doPassword("abc123");
  if(!ok)
    log("wrong password");
}
boolean did= t.doIt();
if(!did)
  log("sorry: " + t.getProblem());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download