Jordi
Jordi

Reputation: 23257

Java Best practice when an exception in caught into java code function

I'd like to know what is the best way or best-practice to handle this kind of situation. Guess a straightforward function like this:

public Object f1() {
    Object result = null;
    try {
        String payload = methodThrowsAnException();         
        result = payload;
    } catch (IOException e) {
        throw new IllegalStateException(e);   <<<<<<<<<<<<<<<
    }

    return result;
}

I'd like to know if it's a good practice:

  1. to re-throw the exception or
  2. return a null when something has been wrong inside.

I don't know if I've explained so well.

Upvotes: 1

Views: 67

Answers (2)

Teddy
Teddy

Reputation: 4243

There is nothing wrong with returning a null from your method if there is a particular scenario where you expect that exception.

Alternatively you can just allow the Exception to bubble up, and be handled by the caller.

When would I catch and re-throw an exception? When I can convey better meaning by throwing a new exception.

Would I include the original exception when I throw a new one? I would do it if it is a unknown/unexpected scenario which requires further debugging.

Let me share some examples:

  1. Something unrecoverable like Out of DB Connection. I would just let the exception bubble up. It should get handled just before it reaches the user, and probably end up in a generic error message like 'Service not available. Please try again later'.
  2. Something application related... such as backup file not found. In that case I will swallow up the FileNotFoundException and instead I will throw a BackupFileMissingException which is specific to my application. Here I don't need to include the FileNotFoundException because it is an expected scenario and there is nothing further to investigate.
  3. I call some other API and they throw an exception, which is not documented. In this case, I will translate it into my application exception such as InterfaceApiException and include the original exception, so that it can be logged at the REST/Action layer along with the root cause.

Upvotes: 0

xenteros
xenteros

Reputation: 15852

Re-throwing caught exception is a bad idea. most often, the stacktrace will contain more or less detailed information about your architecture. This would be to useful for an attacker.

I wouldn't allow my app to get into illegal state because of the user's action. In your case, I would say:

try {
    String payload = methodThrowsAnException();

    result = payload;
} catch (IOException e) {
    throw new IllegalArgumentException(<user's input which caused the exception>);   <<<<<<<<<<<<<<<
}

Upvotes: 1

Related Questions