debugjavaMinor
Java Stream Exception Handling
Viewed 0 times
streamhandlingexceptionjava
Problem
I find this piece of Java code really ugly and cumbersome. How can I refactor it to be more clean and easier to read?
ByteArrayOutputStream out = null;
try {
out = new ByteArrayOutputStream();
workbook.write(out);
return out.toByteArray();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;Solution
From java 7 on you can use the try-with-resources syntax :
Which handles the closing of the Stream, and any excptions that may throw, for you.
In earlier versions of Java, you're pretty much stuck with what you have.
Edit:
It is worth noting that in case you get an exception on the
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
workbook.write(out);
return out.toByteArray();
} catch (Exception e) {
e.printStackTrace();
}
return null;Which handles the closing of the Stream, and any excptions that may throw, for you.
In earlier versions of Java, you're pretty much stuck with what you have.
Edit:
It is worth noting that in case you get an exception on the
close() method, it is still the original exception that is being thrown. The exception on the close() method is then added to that exception as a suppressed exception. You can get at the suppressed exceptions by calling java.lang.Throwable#getSuppressedCode Snippets
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
workbook.write(out);
return out.toByteArray();
} catch (Exception e) {
e.printStackTrace();
}
return null;Context
StackExchange Code Review Q#70283, answer score: 7
Revisions (0)
No revisions yet.