2013-07-03 66 views
1

我確信這個問題一定早已問過,但我無法搜索該帖子。捕獲運行時錯誤Java

我想捕獲線程與原生Java庫生成的運行時錯誤,我可以用什麼方法做同樣的事情?

下面是錯誤的一個例子:

Exception in thread "main" java.io.FileNotFoundException: C:\Documents and Settings\All Users\Application Data\CR2\Bwac\Database\BWC_EJournal.mdb (The system cannot find the path specified) 
    at java.io.FileInputStream.open(Native Method) 
    at java.io.FileInputStream.<init>(FileInputStream.java:106) 
    at java.io.FileInputStream.<init>(FileInputStream.java:66) 
    at CopyEJ.CopyEJ.main(CopyEJ.java:91) 

我想在文件中記錄此錯誤稍後

+2

你下''catch'嘗試,catch'和記錄錯誤附上潛在異常拋​​出的代碼? – NINCOMPOOP

回答

4

回顧剛剛捕獲異常!我的猜測是,目前你的main方法被宣佈拋出Exception,並且你沒有捕獲任何東西......所以這個例外只是傳播出main。請注意例外:

try { 
    // Do some operations which might throw an exception 
} catch (FileNotFoundException e) { 
    // Handle the exception however you want, e.g. logging. 
    // You may want to rethrow the exception afterwards... 
} 

有關異常的更多信息,請參閱exceptions part of the Java tutorial

在本地代碼中出現的異常在這裏是無關緊要的 - 它以完全正常的方式傳播。

+0

比我的回答更好的解釋。 Jon Skeet再次毆打:)你有沒有睡過? – Timmetje

+0

什麼是有效的方式來實現這一點,因爲我在不同級別的代碼中使用file.io. *。我最終會在每個語句中都有一個塊,同樣也有sql異常和解析異常以及 – user2385057

+0

@ user2385057:通常情況下,您只會在相當高的級別上捕獲異常 - 通常*不會*只想記錄並繼續。我有相對較少的try/catch塊 - 但有更多的方法聲明它們可以拋出異常。 –

1

您可以通過try block發現錯誤。

try { 
    // some i/o function 
    reader = new BufferedReader(new FileReader(file)); 

} catch (FileNotFoundException e) { 
    // catch the error , you can log these 
    e.printStackTrace(); 

} catch (IOException e) { 
    // catch the error , you can log these 
    e.printStackTrace(); 
} 

Java Tutorials- Lesson: Exceptions

1

它的好做法用trycatchfinally

try { 
    //Your code goes here  

} catch (Exception e) { 
    //handle exceptions over here 
} finally{ 
    //close your open connections 
}