2013-04-20 30 views
0

這段代碼可能會出現什麼樣的問題? 我覺得即使發生異常,這段代碼也會拋出異常給它的調用者。 所以它不會產生任何麻煩。我能否錯過catch子句來向其調用者拋出異常?

我該如何改進?

public static void cat(File named) { 
    RandomAccessFile input = null; 
    String line = null; 
    try { 
    input = new RandomAccessFile(named, 「r」); 
    while ((line = input.readLine()) != null { 
     System.out.println(line); 
    } 
    return; 
    } finally { 
    if (input != null) { 
     input.close(); 
    } 
    } 
} 
+0

public static void cat(File named)throws IOException'工作嗎? – johnchen902 2013-04-20 08:50:07

+1

它會給編譯錯誤,因爲你沒有處理檢查的異常'IOException' – 2013-04-20 08:53:47

+1

你需要使用'catch'塊來處理它,或者通過改變@ johnchen902 – 2013-04-20 08:54:36

回答

1

此代碼,可能會出現什麼樣的問題?

由於public class FileNotFoundException extends IOException

您可以將方法更改爲:

public static void cat(File named) throws IOException 

現在你不需要的try-catch塊

並且調用者應該捕獲方法拋出的exception

但你爲什麼不想catch的例外?

2

的代碼必須拋出IOException異常 - 嘗試編輯與Eclipse代碼,你也將得到一個建議拋出異常。

此外,Java 1.7有新概念「try-with-resources」 - 請參閱下面的try語句。 try (...)中使用的資源已自動關閉。

public static void cat(File named) throws IOException 
{ 
    try (RandomAccessFile input = new RandomAccessFile(named, "r")) 
    { 
     String line = null; 
     while ((line = input.readLine()) != null) 
     { 
      System.out.println(line); 
     } 
    } 
} 
+3

建議的方法簽名把它返回給調用者如果你強制該方法拋出任何異常 – shiladitya 2013-04-20 08:59:02

+2

哦,不需要try-catch-finally塊嗎? - 「試用資源」用於關閉文件 - 如果你不知道自己在說什麼,不需要投票表決權,對吧? – 2013-04-20 09:00:44

0

在您的方法中添加throws聲明,然後此方法的調用者應爲此異常嘗試catch塊。

public static void cat(File named) throws IOException { 
     RandomAccessFile input = null; 
     String line = null; 
     try { 
     input = new RandomAccessFile(named, "r"); 
     while ((line = input.readLine()) != null){ 
      System.out.println(line); 
     } 
     return; 
     } finally { 
     if (input != null) { 
      input.close(); 
     } 
     } 
    } 
    //caller 
    try{ 
    Class.cat(new File("abc.txt")); 
    }catch(IOException e) 
    { 
     // 
    } 
+0

如果你強制該方法拋出任何異常 – shiladitya 2013-04-20 08:59:30

+0

嘗試最後關閉資源,catch塊不在那裏,你不需要try-catch-finally塊。 – Ahsan 2013-04-20 09:48:05