2014-09-01 80 views
-14

在一次採訪中,一位HR問我這個問題「沒有嘗試就有catch塊,我的程序將會成功運行,這對於doind有一個方法,那是什麼方法?」有沒有嘗試和最後有catch塊?

我可以使用catch塊而不使用try/finally塊嗎? 請幫幫我!

+1

不,你不能。 – sp00m 2014-09-01 10:14:04

+5

在您的IDE中嘗試! – Betlista 2014-09-01 10:14:09

+1

你有試過編譯它嗎?在線閱讀基本文檔? – cchantep 2014-09-01 10:14:29

回答

2

不,你不能。沒有試圖做任何事,你想要捕捉哪個異常?說得通 ?。 No.

6

不可能有catch塊沒有try

但有可能有tryfinally塊沒有catch

UPDATE(感謝@fabian爲擡頭):

你也可以有try with resources,它是try沒有catchfinally塊。

下面有定義從Oracle's document

試戴與資源語句是聲明瞭一個或多個資源的try語句。資源是程序結束後必須關閉的對象。 try-with-resources語句確保每個資源在語句結束時都關閉。任何實現java.lang.AutoCloseable的對象(包含所有實現java.io.Closeable的對象)都可以用作資源。

這裏是嘗試,與資源的示例代碼:

// Open zip file and create output file with 
// try-with-resources statement 

try (
    java.util.zip.ZipFile zf = 
     new java.util.zip.ZipFile(zipFileName); 
    java.io.BufferedWriter writer = 
     java.nio.file.Files.newBufferedWriter(outputFilePath, charset) 
) { 
    // Enumerate each entry 
    for (java.util.Enumeration entries = 
          zf.entries(); entries.hasMoreElements();) { 
     // Get the entry name and write it to the output file 
     String newLine = System.getProperty("line.separator"); 
     String zipEntryName = 
      ((java.util.zip.ZipEntry)entries.nextElement()).getName() + 
      newLine; 
     writer.write(zipEntryName, 0, zipEntryName.length()); 
    } 
+1

如果嘗試使用資源,也可以使用'try'既不帶'catch'也不帶'finally'塊。 – fabian 2014-09-01 10:18:53