Of course, you do not want the three separate blocks to be with the code as it is. In the first block, you find an error when setting up writer , but then in subsequent blocks you use writer , which does not make sense if the first block fails. As a result, you will get a NullPointerException when an I / O error occurs - not perfect .:-)
There's a lot of room for style in this stuff, but here's a pretty standard reinterpretation of your function. It uses only two blocks (although you can add the third part, see comments in the code):
public void save(Object object, File file) { BufferedWriter writter = null; try { writter = new BufferedWriter(new FileWriter(file)); Dictionary dictionary = (Dictionary)object; ArrayList<Card> cardList = dictionary.getCardList(); for (Card card: cardList) { String line = card.getForeignWord() + " / " + card.getNativeWord(); writter.write(line);
Note in the finally block: here you can handle the usual case (in this case the writter will be null ), or you can handle the exception that you did not catch (this isnโt unusual, one of the main points of the exceptions is handling what suits the this level, and transfer anything else before the caller). If writter is !null , close it. And when you close it, eat any exception that happens, or you close the original. (I have utility functions for closing things while using an exception, for this situation. For me it could be writter = Utils.silentClose(writter); [ silentClose always returns null ]). Now in this code you can not expect other exceptions, but A) you can change this later, and B) a RuntimeException can occur at any point. Itโs best to get used to using the template.
source share