2013-05-02 85 views
1

在Java中,如果可以在while循環中引發異常,並且在循環內由try-catch塊包圍的語句,則使用try-catch塊包圍的循環之間存在差異。有沒有一種方法可以在不中斷Java環境的情況下捕獲異常?

例如,下面的代碼段是不同的:


片段1:

try { 
    for (File file : files) { 
     FileInputStream fis = new FileInputStream(file); 
     System.out.println("OK!"); 
    } 
} 
catch (FileNotFoundException exc) { 
    System.out.println("Error!"); 
} 

^此代碼段打破循環,如果一個FileNotFoundException被拋出。因此,如果文件無法讀取,那麼循環會中斷,Java將停止讀取更多文件。


片段2:

for (File file : files) { 
    try { 
     FileInputStream fis = new FileInputStream(file); 
     System.out.println("OK!"); 
    } 
    catch (FileNotFoundException exc) { 
     System.out.println("Error!"); 
    } 
} 

^如果將引發異常,如果發生異常,則代碼捕捉異常並繼續到該代碼段不破環下一個元素在files。換句話說,它不會停止閱讀文件。


現在我想讀某個文件的目錄中(比如bananas.xml),並且,如果unregarded該文件是可讀的或不XML文件的元數據文件,這可能不是需要爲程序運行 - ,讀取相應目錄(這是香蕉):

File main = new File("/home/MCEmperor/test"); 
File fruitMeta = new File(main, "bananas.xml"); 
FileInputStream fruitInputStream = new FileInputStream(fruitMeta); // This code COULD throw a FileNotFoundException 
// Do something with the fruitInputStream... 

File fruitDir = new File(main, "bananas"); 
if (fruitDir.exists() && fruitDir.canRead()) { 
    File[] listBananas = fruitDir.listFiles(); 
    for (File file : listBananas) { 
     FileInputStream fis = new FileInputStream(file); // This code COULD throws a FileNotFoundException 
     // Do something with the fis... 
    } 
} 

現在兩行代碼段的上方可以拋出FileNotFoundException,我不想打破循環。

現在有沒有辦法讓一個try catch塊捕獲兩條線,如果拋出異常但沒有破壞for -loop?

+2

我不認爲這是可能的。爲什麼不使用兩個不同的try-catch塊? – nullptr 2013-05-02 20:31:29

+2

只是我的一個普遍的異常,但你正在使用一個例外,你期待的東西。這聽起來不像是一個例外,但是對於'if(!exists){continue}'來說是個好例子。 – Maple 2013-05-02 20:35:24

+0

有幾個原因導致FileNotFoundException被拋出;在Windows中,出於某種奇怪的原因,該文件無法訪問時也會引發此異常。 – 2013-05-02 20:39:17

回答

4

這樣的事情呢?

FileInputStream fruitInputStream = getFileInputStream(fruitMeta); 
... 
fis = getFileInputStream(file); 

private static FileInputStream getFileInputStream(File file) { 
    try { 
     return new FileInputStream(file); 
    catch(FileNotFoundException e) { 
     return null; 
    } 
} 
+0

編輯了一個不安全的替代解決方案。 – 2013-05-02 20:47:36

相關問題