2010-04-07 47 views
2

try在java中做什麼?在java中嘗試做什麼?

+14

有沒有嘗試只有做 – 2010-04-07 02:20:00

+1

以前沒有問過這個問題嗎?哦,不要忘了谷歌 – 2010-04-07 03:34:17

+0

嗯,做和(!做)。 – MJB 2010-04-08 20:47:53

回答

4

try/catch/finally結構允許你指定在情況下例外try塊(catch)內發生運行代碼,和/或代碼,將try塊後運行,即使一個異常已經發生(finally )。

try{ 
    // some code that could throw MyException; 
} 
catch (MyException e){ 
    // this will be called when MyException has occured 
} 
catch (Exception e){ 
    // this will be called if another exception has occured 
    // NOT for MyException, because that is already handled above 
} 
finally{ 
    // this will always be called, 
    // if there has been an exception or not 
    // if there was an exception, it is called after the catch block 
} 

無論發生什麼,最終塊對於釋放資源(例如數據庫連接或文件句柄)都很重要。如果沒有它們,你將不會有一個可靠的方法在異常情況下執行清理代碼(或者在try塊中返回,中斷,繼續等等)。

+0

你能深入一點了解爲什麼Finaly塊很重要嗎? – David 2010-04-07 02:33:14

0

你們談了 「的try/catch」 塊。它用於捕獲「try/catch」內代碼塊內可能發生的異常。異常將在「catch」語句中處理。

0

它允許您爲一段代碼定義一個異常處理程序。該代碼將被執行,如果發生任何「異常」(空指針引用,I/O錯誤等),則會調用適當的處理程序(如果已定義)。

欲瞭解更多信息,請參閱維基百科上的Exception Handling

3

它可以讓你嘗試的操作,並在拋出異常的情況下,你可以處理它優雅而不是把它向上冒泡並暴露給用戶一個醜陋的,而且往往無法恢復,錯誤:

try 
{ 
    int result = 10/0; 
} 
catch(ArithmeticException ae) 
{ 
    System.out.println("You can not divide by zero"); 
} 

// operation continues here without crashing 
1

try經常與catch一起用於運行時可能出錯的代碼,一個知道爲的事件引發異常。它用於指示機器嘗試運行代碼,並捕獲發生的任何異常。因此,例如,如果您要求打開一個不存在的文件,語言會警告您出現了問題(即通過了一些錯誤的輸入),並允許您將帳戶因爲它通過將它包含在try..catch塊中而發生。

File file = null; 

try { 
    // Attempt to create a file "foo" in the current directory. 
    file = File("foo"); 
    file.createNewFile(); 
} catch (IOException e) { 
    // Alert the user an error has occured but has been averted. 
    e.printStackTrace(); 
} 

可選finally子句可以一個try..catch塊之後被用於確保一定的清理(如關閉文件)總是發生:

File file = null; 

try { 
    // Attempt to create a file "foo" in the current directory. 
    file = File("foo"); 
    file.createNewFile(); 
} catch (IOException e) { 
    // Alert the user an error has occured but has been averted. 
    e.printStackTrace(); 
} finally { 
    // Close the file object, so as to free system resourses. 
    file.close(); 
} 
+0

請注意,「catch」也是可選的。 – Thilo 2010-04-07 03:13:42

1

異常處理