Seby
Seby

Reputation: 262

Java try-with resource warning from Eclipse

Why for Eclipse this is to be managed with a try-with arm?

BufferedReader reader = null;
try {
  if (condition) {
    try {
      reader = method1();
    } catch (Exception e) {
      ...
    }
  }
  if (reader == null) {
    reader = method2();
  }

  do things ...
} catch(Exception e) {
  ...
} finally {
  if (reader != null) {
    reader.close();
  }
}

There is a better way to handle this case? or just a junk warning from eclipse?

This case is not valid:

try (BufferedReader reader = null) {
  if (condition) {
    reader = method1();
  } else {
    reader = method2();
  }

  do things ...
}

Upvotes: 0

Views: 1941

Answers (5)

Matt
Matt

Reputation: 116

You don't necessarily need a Callable or lambda expression as in Seby's answer.

Given that the problem is simple enough you can simply use a ternary operator, which works in all versions of java.

final String s = "abc";

try (BufferedReader reader = (condition) ? method1() : method2();) {

  do things ...

} catch (Exception e) {
  ...
}

Upvotes: 1

Seby
Seby

Reputation: 262

Best way imho, clear and concise :

final String s = "abc";

try (BufferedReader reader = new Callable<BufferedReader>() {
  @Override
  public BufferedReader call() throws Exception {
    if (condition) {
      return method1();
    } 
    return method2();

    // different scope, s needs final keyword
  }
}.call()) {

  do things ...

} catch (Exception e) {
  ...
}

Also easier in java 8 :

String s = "abc";

try (BufferedReader reader = () -> {
  if (condition) {
    return method1();
  } 
  return method2();

  // same scope, s does not need final keyword
}) {

  do things ...

} catch (Exception e) {
  ...
}

Upvotes: 0

Pshemo
Pshemo

Reputation: 124255

As Java Language Specification states in jls-14.20.3

A resource declared in a ResourceSpecification is implicitly declared final (§4.12.4) if it is not explicitly declared final.

So you can't change it in your try block. If you want to be able to change it use standard try-catch-finally block. Other option would be deciding about correct resource before useing it with try-with-resources.

Upvotes: 1

D3X
D3X

Reputation: 547

you can use a function which has a return type of BufferedReader in which you can use your conditional call, this function can be invoked from main only if some specific condigion that you are looking for is met.

private BufferedReader createReader(!XYZ){
if(a>b)
return abc();
else
return def();
}

public static void main(String[] args){
createReader(!XYZ);
}

Upvotes: 0

Puce
Puce

Reputation: 38132

Try:

try (BufferedReader reader = createBufferedReader(condition)) {
  do things ...
}

private BufferedReader createBufferedReader(boolean condition){
  if (condition) {
    return method1();
  } else {
    return method2();
  }
}

Upvotes: 1

Related Questions