tags:

views:

415

answers:

5

In the following scenario, I was trying to see how to handle this code and it how it relates to Runtimexception. I have read that is generally better to throw runtime exceptions as opposed to rely on static exceptions. And maybe even better to catch a static checked exception and throw an unchecked exception.

Are there any scenarios where it is OK to catch a static exception, possibly the catch-all Exception and just handle the exception. Possibly log an error message and continue on.

In the code below, in the execute1 method and execute2 method, let us say there is volatile code, do you catch the static exception and then rethrow? Or possibly if there are other errors:

if (null == someObj) { throw new RuntimeException(); }

Is this an approach you use?

Pseudo Code:

public class SomeWorkerObject {
  private String field1 = "";
  private String field2 = "";

  public setField1() { }
  public setField2() { }

  // Do I throw runtime exception here?
  public execute1() {
    try {
    // Do something with field 1
    // Do something with field 2
    } catch(SomeException) {
      throw new RuntimeException();
    }
  }

  // Do I throw runtime exception here?
  public execute2() {
    try {
    // Do something with field 1
    // Do something with field 2
    } catch(SomeException) {
      throw new RuntimeException();
    }

  }

}

public class TheWeb {

 public void processWebRequest() {

    SomeWorkerObject obj = new SomeWorkerObject();
    obj.setField1("something");
    obj.setField2("something");

    obj.execute1(); 
    obj.execute2();
    // Possibility that runtime exception thrown?

    doSomethingWith(obj);
 }
}

I have a couple of problems with this code. There are times when I don't want a runtimeexception to be thrown because then execution stops in the calling method. It seems if I trap the errors in the method, maybe I can continue. But I will know if I can continue later on the program.

In the example above, what if obj.execute1() throws a Runtimeexception, then the code exits?

Edited: This guy seems to answer a lot of my questions, but I still want to hear your opinions.

http://misko.hevery.com/2009/09/16/checked-exceptions-i-love-you-but-you-have-to-go/

"Checked exceptions force me to write catch blocks which are meaningless: more code, harder to read, and higher chance that I will mess up the rethrow logic and eat the exception."

+2  A: 

There are times when I don't want a runtimeexception to be thrown because then execution stops in the calling method. It seems if I trap the errors in the method, maybe I can continue. But I will know if I can continue later on the program.

You have the right idea. The advice about throwing RuntimeException is that it doesn't require the caller to use a try-block or a 'throws' clause.

If your code can recover from an exception than it really should catch it and not throw anything.

Kelly French
That is what I was thinking. It seems like the Internet disagrees with me.
Berlin Brown
+1  A: 

One of the first rules about exceptions is to not abuse them to pass state in your application. They should be used for exceptional situations, not as alternative return values.

The second rule is to catch exceptions at the level you process them. Catch and rethrow does not add much. Any cleanup code in your method should be done in a finally block.

In my opinion catching checked exceptions and rethrowing them as runtime exceptions is abusing the system. It feels like working around the "limitations" of design by contract instead of using those "limitations" to get a more robust application.

rsp
+7  A: 

When catching an exception and throwing RuntimeException instead, it is important to set the original exception as a cause for the RuntimeException. i.e.

throw new RuntimeException(originalException).

Otherwise you will not know what was the problem in the first place.

Bozho
+1: an absolute must.
BalusC
That is a good point.
Berlin Brown
And if not rethrowing, please add some text explaining what went wrong. The guy who has to fix it will want to know :)
extraneon
+1  A: 

Whether or not to handle an exception or simply rethrow it depends on your use case.

For example, if you're reading a file to load data into your application, and some IO error occurs, you're unlikely to recover from the error, so rethrowing the error to the top and consequently terminating the application isn't a bad course of action.

Conversely, if you're anticipating recoverable errors then you should absolutely catch and handle the errors. For example, you may have users entering data in a form. If they enter data incorrectly, your input processing code may throw an exception (e.g. NumberFormatException when parsing a malformed number string). Your code should catch these exceptions and return an error the user, prompting for correct input.

On an additional note, it's probably bad form to wrap all your exceptions with RuntimeException. If your code is going to be reused somewhere else, it is very helpful to have checked exceptions to signify that your code can fail in certain ways.

For example, assume your code is to parse configuration data from a file. Obviously, an IO error may occur, so you will have to catch an IOException somewhere in your code. You probably won't be able to do anything about the error, so you will have to rethrow it. However, someone calling into your code may well be able to handle such an error, for example by backing off to configuration defaults if the configuration can't be loaded from the file. By marking your API with checked exceptions, someone using your code can clearly see where an error may occur, and can thus write the error handling code at the appropriate place. If instead you simply throw a RuntimeException, the developer using your code won't be aware of possible errors until they creep up during testing.

toluju
+1  A: 

Rethrowing checked exceptions as unchecked exceptions should only be done if you are sure that the checked exception is not to be expected.

Here's a typical example:

try {
    hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
} catch (NoSuchAlgorithmException e) {
    // Unexpected exception. "MD5" is just hardcoded and supported.
    throw new RuntimeException("MD5 should be supported?", e);
} catch (UnsupportedEncodingException e) {
    // Unexpected exception. "UTF-8" is just hardcoded and supported.
    throw new RuntimeException("UTF-8 should be supported?", e);
}
BalusC
For these two cases, I would suggest throwing an AssertionError instead; it seems to fit better, semantically speaking.
Rob
It was just a basic example, nevertheless a good suggestion :) +1.
BalusC
"Rethrowing checked exceptions as unchecked exceptions should only be done if you are sure that the checked exception is not to be expected."That is kind of how I normally proceed. But there still doesn't seem to be a set of concrete rules on how to handle Exceptions.I guess the developer community is still undecided on this."Should only be done if you are sure that the checked exception is not to be expected."For example...
Berlin Brown
For the remnant I just use the **`throws`** clause wisely.
BalusC