Is there a way to catch exceptions without breaking loop in Java? -


in java, there's difference between loop surrounded try-catch block if exception thrown inside while loop, , statement surrounded try-catch block inside loop.

for instance, following code snippets different:


snippet 1:

try {     (file file : files) {         fileinputstream fis = new fileinputstream(file);         system.out.println("ok!");     } } catch (filenotfoundexception exc) {     system.out.println("error!"); } 

^this code snippet breaks loop if a filenotfoundexception is thrown. if file cannot read, loop breaks , java stop reading further files.


snippet 2:

for (file file : files) {     try {         fileinputstream fis = new fileinputstream(file);         system.out.println("ok!");     }     catch (filenotfoundexception exc) {         system.out.println("error!");     } } 

^this code snippet not break loop if exception thrown, if exception occurs, code catches exception , continues next element in files. other words, won't stop reading files.


now want read file in directory (say bananas.xml), and, unregarded if file readable or not—the xml file metadata file, might not required program run—, read corresponding directory (which bananas):

file main = new file("/home/mcemperor/test"); file fruitmeta = new file(main, "bananas.xml"); fileinputstream fruitinputstream = new fileinputstream(fruitmeta); // code throw filenotfoundexception // fruitinputstream...  file fruitdir = new file(main, "bananas"); if (fruitdir.exists() && fruitdir.canread()) {     file[] listbananas = fruitdir.listfiles();     (file file : listbananas) {         fileinputstream fis = new fileinputstream(file); // code throws filenotfoundexception         // fis...     } } 

now 2 lines in snippet above may throw filenotfoundexception , don't want break loop.

now there way make 1 try-catch block catches both lines if exception thrown, without breaking for-loop?

how this?

fileinputstream fruitinputstream = getfileinputstream(fruitmeta); ... fis = getfileinputstream(file);  private static fileinputstream getfileinputstream(file file) {     try {         return new fileinputstream(file);     catch(filenotfoundexception e) {         return null;     } } 

Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -