views:

901

answers:

4

Let's say I can a set of statements:

try {
  String a = getProperty("a");
  String b = getProperty("b");
  String c = getProperty("c");
} catch(Exception e) {

}

Now, lets say property b was not found and the function throws an exception. In this case, how would I just continue or perhaps set b to null without having to write a try-catch block for each property? I mean, a,b,c exist but sometime they might not be found at all during which an exception is thrown.

+5  A: 

You have to put a try-catch around each statement. There is no continue (like there is in ON ERROR ... RESUME blocks in VB). Instead of:

String a = null;
try {
  a = getProperty("a");
} catch(Exception e) {
  ...
}
String b = null;
try {
  b = getProperty("b");
} catch(Exception e) {
  ...
}
String c = null;
try {
  c = getProperty("c");
} catch(Exception e) {
  ...
}

you could write:

public String getPropertyNoException(String name) {
  try {
    return getProperty(name);
  } catch (Exception e) {
    return null;
  }
}

Personally I think a getProperty() is a poor candidate for throwing exceptions just for all this extra boilerplate required

cletus
Ah... I thought I could get away using a simpler approach.. Thanks..
Legend
Yeah... that getProperty comes from a different library and I didn't really want to touch that part.
Legend
+2  A: 

Since you are using the same function each time you might be able to put this in a loop:

String[] abc = new String[3];
String[] param = {"a", "b", "c"};
for (int i = 0; i < 3; i++) {
    try {
      abc[i] = getProperty(param[i]);
    } catch(Exception e) {

    }
}

but this is rather contrived and would only be useful for a large number of properties. I suspect you will have to simple write 3 try-catch.

peter.murray.rust
+10  A: 

Assuming you can't change the function so that it returns null when the property isn't found, you are kind of stuck wrapping everything in its own try catch block -- especially if you want for every value that can be retrieved to be retrieved (as opposed to letting the first value that fails cancel the whole operation.)

If you have a lot of these properties to retrieve, perhaps it would be cleaner to write a helper method to use:

String getPropertySafely(String key) {
   try {
      return getProperty(key);
   } catch (Exception e) {
      return null;
   }
}
Xanatos
This looks very interesting! Thanks
Legend
I would name it "getPropertyQuietly" just because they use that naming convention in the Jakarta Commons IO (the methods closeQuietly in the IOUtils class)
Ravi Wallau
+1 Ravi - A major pet peeve of mine is swallowing exceptions. If you're going to do so, at least make it obvious based on the name of the method. (Clean Code)
Elliot
+1  A: 

You should reconsider how getProperty is handled if you plan to use many of them because there isn't a plain way to do it.

You can exploit finally statement but you still need a try-catch for every call.

Jack