java - Close file in finally block doesn't work -



java - Close file in finally block doesn't work -

try { filereader fr = new filereader(file); bufferedreader br = new bufferedreader(fr); string line = null; } grab (filenotfoundexception fnf) { fnf.printstacktrace(); } { fr.close(); }

the fr.close() shows error:

fr cannot resolved

i had read closing file in block practice. doing wrong?

the variable fr has scope within try block. out of scope in block. need declare before try block:

filereader fr = null; seek { fr = new filereader(file); bufferedreader br = new bufferedreader(fr); string line = null; } grab (filenotfoundexception e) { e.printstacktrace(); } { if (fr != null) { seek { fr.close(); } grab (ioexception e) { // unrecoverable. study , move on e.printstacktrace(); } } }

this quite mutual pattern of code, it's remember future similar situations.

consider throwing ioexception method - printing track traces isn't helpful callers, and wouldn't need nested seek grab around fr.close()

java try-catch-finally

Comments

Popular posts from this blog

How do I check if an insert was successful with MySQLdb in Python? -

delphi - blogger via idHTTP : error 400 bad request -

postgresql - ERROR: operator is not unique: unknown + unknown -