Java unreported exception -


while learning java stumble upon error quite often. goes this:

unreported exception java.io.filenotfound exception; must caught or declared thrown.

java.io.filenotfound example, i've seen many different ones. in particular case, code causing error is:

outputstream out = new bufferedoutputstream(new fileoutputstream(new file("myfile.pdf"))); 

error disappears , code compiles & runs once put statement inside try/catch block. it's enough me, not.

first, examples i'm learning not use try/catch , should work nevertheless, apparently.

whats more important, when put whole code inside try/catch cannot work @ all. e.g. in particular case need out.close(); in finally{ } block; if statement above inside try{ }, finally{} doesnt "see" out , cannot close it.

my first idea import java.io.filenotfound; or relevant exception, didnt help.

what you're referring checked exceptions, meaning must declared or handled. standard construct dealing files in java looks this:

inputstream in = null; try {   in = new inputstream(...);   // stuff } catch (ioexception e) {   // whatever } {   if (in != null) {     try {       in.close();     } catch (exception e) {     }   } } 

is ugly? sure. verbose? sure. java 7 make little better arm blocks until you're stuck above.

you can let caller handle exceptions:

public void dostuff() throws ioexception {   inputstream in = new inputstream(...);   // stuff   in.close(); } 

although close() should wrapped in finally block.

but above function declaration says method can throw ioexception. since that's checked exception caller of function need catch (or declare caller can deal , on).


Comments

Popular posts from this blog

c++ - Convert big endian to little endian when reading from a binary file -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

unicode - Are email addresses allowed to contain non-alphanumeric characters? -