2013-05-12 112 views
1

我有這2種方法來從文件中讀取一些整數並將它們插入樹中。如果找到該文件,它工作正常,但如果找不到該文件,則不會打印「文件未找到」。爲什麼它沒有進入捕獲聲明?謝謝!嘗試捕獲錯誤

public static void openF(Tree myT) 
{ 

    try 
    { 
     x=new Scanner(new File("Number.txt")); 
     readF(myT); 
    } 
    catch(Exception e) 
    { 
     System.out.println("File not found"); 
    } 
} 


// to read from the file 
public static void readF(Tree myT) 
{ 

    while(x.hasNext()) //keeps going till it reaches the end of file 
    { 
     int a =x.nextInt(); 
     myT.insert(a); //insert in tree 

    } 
} 
+0

如果將空指針傳遞給它,文件的構造函數只會拋出異常。如果文件不存在,則不會拋出異常。掃描器構造函數是否拋出任何異常? readF方法沒有 – EdH 2013-05-12 10:48:37

回答

2

我測試你的代碼的簡化版本:

public static void main(String[] args) { 
    try { 
     new Scanner(new File("H:\\Hello.txt")); 
     System.out.println("The file exists."); 
    } catch (Exception e) { 
     System.out.println("File not found: " + e.getMessage()); 
    } 
} 

當該文件存在,它打印The file exists.。如果不是,則打印File not found: H:\Hello.txt (The system cannot find the file specified)

所以不,catch塊按預期運行。錯誤在代碼中的其他位置,但由於您沒有提供完整的代碼,也沒有實際編譯的部分(x沒有聲明),所以我們無法猜測實際錯誤的位置。