Code snippet in Try

Asked

Viewed 77 times

2

I was making corrections in a class and I came across the following code, I didn’t know it was possible and I never stopped to think, but why is this valid? I mean first line of the Try. For me Try/catch always been in the format:

try{
...
}catch(Exception e){
...
} 

The following code is the same as writing in the "syntax" above?

try (FileInputStream fs = new FileInputStream(templateFile)) {
                Workbook wb = write(validation, WorkbookFactory.create(fs), planilha);
                File file = relatorioPlanilhaDAO.exportSheet(planilha.getNomeHash());
                FileOutputStream fout = new FileOutputStream(file);
                if (wb != null) {
                    wb.write(fout);
                } else {
                    Log.error(this, "Erro ao escrever no arquivo.");
                    throw new InternalServerErrorException("Erro ao exportar relatório.");
                }
                fout.flush();
                fout.close();

                return file;
            } catch (IOException e) {
                Log.info(this, "Erro ao obter planilha.", e);
                throw new NotFoundException("Erro ao exportar planilha.", e);
            } catch (InvalidFormatException | IllegalArgumentException e) {
                Log.error(this, "Formato de planilha inválido.", e);
                throw new InternalServerErrorException("Formato de planilha inválido.", e);
            }
  • see this issue @Danielamarquesdemora http://answall.com/questions/71638/como-n%C3%A3o-include-o-Finally-e-yet-yes-close-io-streams-Connections-statement

1 answer

5


It’s not the same.

The second is a try with Resources, introduced in Java 7, which briefly is a try declaring an object AutoCloseable, in your case a FileInputStream. This means that if there is failure or not, the FileInputStream will be automatically closed.

It would be similar if the first code were like this:

try{
  ...
  FileInputStream fs = new FileInputStream(templateFile);
}catch(Exception e){
  ...
}
finally {
  fs.close();
}

You can create your own object AutoCloseable, simply implementing this class or the Closeable.

A good article in Portuguese to better understand can be seen here: http://blog.globalcode.com.br/2011/10/o-novo-try-no-java-7-por-uma-linguagem.html

Browser other questions tagged

You are not signed in. Login or sign up in order to post.