Code snippet in Try

2

I was making corrections in a class and I came across the following code, did not know it was possible and never stopped to think, but why is this valid? I'm referring to the first line of Try. For me try / catch has always been in the format:

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

Is the following code the same as writing in the above syntax?

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);
            }
    
asked by anonymous 30.06.2015 / 19:00

1 answer

5

It's not the same thing.

The second is a try with resources , introduced in Java 7, which is briefly a try that declares an object AutoCloseable , in your case a FileInputStream . This means that failing or not, FileInputStream will be closed automatically.

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 yourself by simply implementing this class or Closeable .

A good article in Portuguese to understand better can be seen here: link

    
30.06.2015 / 19:13