Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Try-Catch-Continue?

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.

like image 432
Legend Avatar asked Nov 25 '09 03:11

Legend


People also ask

Does Java continue after try-catch?

You have to put a try-catch around each statement. There is no continue (like there is in ON ERROR ...

How do you continue to try after a catch?

If an exception is caught and not rethrown, the catch() clause is executed, then the finally() clause (if there is one) and execution then continues with the statement following the try/catch/finally block.

Can we use continue in catch block?

You only need continue if you have code after it, and want start at the top of the loop again.

Can we ignore catch block in Java?

In the catch block you can mention the exception and ignore keyword for that exception.


1 Answers

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;
   }
}
like image 107
Xanatos Avatar answered Oct 12 '22 23:10

Xanatos