i expecting buffered reader , file reader close , resources released if exception throw.
public static object[] fromfile(string filepath) throws filenotfoundexception, ioexception { try (bufferedreader br = new bufferedreader(new filereader(filepath))) { return read(br); } }
however, there requirement have catch
clause successful closure?
edit:
essentially, above code in java 7 equivalent below java 6:
public static object[] fromfile(string filepath) throws filenotfoundexception, ioexception { bufferedreader br = null; try { br = new bufferedreader(new filereader(filepath)); return read(br); } catch (exception ex) { throw ex; } { try { if (br != null) br.close(); } catch(exception ex) { } } return null; }
it's correct , there's no requirement catch
clause. oracle java 7 doc says resource closed regardless of whether exception thrown or not.
you should use catch
clause if want react upon exception. catch
clause executed after resource closed.
here's snippet oracle's tutorial:
the following example reads first line file. uses instance of bufferedreader read data file. bufferedreader resource must closed after program finished it:
static string readfirstlinefromfile(string path) throws ioexception { try (bufferedreader br = new bufferedreader(new filereader(path))) { return br.readline(); } } // in example, resource declared in try-with-resources statement bufferedreader.
... because bufferedreader instance declared in try-with-resource statement, closed regardless of whether try statement completes or abruptly (as result of method bufferedreader.readline throwing ioexception).
edit
regarding new edited question:
the code in java 6 executes catch
, afterwards finally
block. causes resources still potentially opened in catch
block.
in java 7 syntax, resources closed before catch
block, resources closed during catch
block execution. documented in above link:
in try-with-resources statement, catch or block run after resources declared have been closed.
Comments
Post a Comment