문제

In java, one may easily need to do something such as instantiate a BufferedWriter object. This could be done in the following fashion:

File outFile = new File("myTestFile.txt");

BufferedWriter w = null;
try { w = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8")); }
catch (FileNotFoundException|UnsupportedEncodingException e) { System.out.println(e.getMessage()); }

w.write("Test string");
w.newLine();

Note that w is declared before the try-catch block. This is so that it is within the proper scope to use the variable after the try-catch. It is initialized with a null pointer, otherwise an IDE like netbeans will warn that the variable may have not been assigned. HOWEVER, the IDE still complains that when you reach w.write(), w could possibly have a null value. This makes perfect sense, since the try block might fail!

Is there a more elegant and sensible way to do this, in ways which will not cause logical problems like what my IDE reminds me of above?

I realize i can wrap EVERYTHING that w does in the try block, but this is not feasible for my task. How else could i initialize w, if there is another option?

Thanks!

도움이 되었습니까?

해결책 2

Consider a try-with-resources, if you're using Java 7.

try (BufferedWriter w = new BufferedWriter
    (new OutputStreamWriter(
        new FileOutputStream(outFile), "utf-8"))) {
    w.write("Test string");
    w.newLine();
} catch (IOException ex) {
    ex.printStackTrace();
}

If your problem is the amount of code that would be inside the try block, consider factoring that code into a method.

try (BufferedWriter w = new BufferedWriter
    (new OutputStreamWriter(
        new FileOutputStream(outFile), "utf-8"))) {
    writeEverythingINeed(w);
} catch (IOException ex) {
    ex.printStackTrace();
}

Alternatively, you have no option but to enclose the remaining statements inside an if.

BufferedWriter w = null;
try { w = ... }
catch (FileNotFoundException | UnsupportedEncodingException e) {
    System.out.println(e.getMessage());
}

if (w != null) {
    w.write("Test string");
    w.newLine();
}

Again, the block inside the if may be refactored into a method.

다른 팁

You simply have to wrap everything, because that's Java language design - otherwise (given that there is no such concept as Exceptions), you would have to check every call to an otherwise Exception-throwing operation if your writer is still valid, which is even less feasible.

See try-catch blocks more like a special section under watch, where bad and exceptional stuff can happen without fully breaking your application.

First, you have no choice but to wrap below lines into a try-catch:

w.write("Test string");
w.newLine();

as they are both capable of throwing IOExceptions (you can alternatively declare a throws clause though).

In Eclipse, I don't see any reason that the IDE will complain that w can be null, as you've already explicitly initialized it.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top