try
在java中做什麼?在java中嘗試做什麼?
回答
的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塊中返回,中斷,繼續等等)。
你能深入一點了解爲什麼Finaly塊很重要嗎? – David 2010-04-07 02:33:14
你們談了 「的try/catch」 塊。它用於捕獲「try/catch」內代碼塊內可能發生的異常。異常將在「catch」語句中處理。
它允許您爲一段代碼定義一個異常處理程序。該代碼將被執行,如果發生任何「異常」(空指針引用,I/O錯誤等),則會調用適當的處理程序(如果已定義)。
欲瞭解更多信息,請參閱維基百科上的Exception Handling。
它可以讓你嘗試的操作,並在拋出異常的情況下,你可以處理它優雅而不是把它向上冒泡並暴露給用戶一個醜陋的,而且往往無法恢復,錯誤:
try
{
int result = 10/0;
}
catch(ArithmeticException ae)
{
System.out.println("You can not divide by zero");
}
// operation continues here without crashing
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();
}
請注意,「catch」也是可選的。 – Thilo 2010-04-07 03:13:42
異常處理
- 1. 找到Server.CreateObject正在嘗試做什麼
- 2. CakePHP 2 Auth在嘗試登錄時什麼都不做什麼
- 3. SQL注入嘗試,這個查詢嘗試做什麼?
- 4. 在java中做什麼?
- 5. java在void中做什麼?
- 6. Collections.unmodifiableSet()在Java中做什麼?
- 7. cipher.update在java中做什麼?
- 8. fpstrict在Java中做什麼?
- 9. 什麼是outData.writeInt()在Java中做什麼?
- 10. 什麼嘗試可以在PHP文件中做?
- 11. 在Java中,爲什麼在嘗試顯示FileNotFoundException時收到NullPointerException?
- 12. 嘗試,美中不足的是:做什麼,如果TRY成功
- 13. 嘗試從SwingWorker done()方法中繪製JPanel什麼也不做
- 14. 微軟商業智能。我正在嘗試做什麼?
- 15. 什麼下面的語句在執行的嘗試做
- 16. Django是我正在嘗試做什麼的合適工具?
- 17. 嘗試執行SQL注入攻擊 - 他們在做什麼?
- 18. 爲什麼在Java中的嘗試 - 以資源
- 19. Java中'0'做什麼?
- 20. java目前在做什麼?
- 21. 「做」在這裏做什麼? (java)
- 22. java -Dnop做什麼?
- 23. 在Perl中做什麼=〜做什麼?
- 24. >>在java中做什麼?
- 25. 在Java方法中做什麼?
- 26. 在Java中File.canExecute()究竟做了什麼?
- 27. j + = j ++在Java中做什麼?
- 28. 在Java中做什麼<>?
- 29. | =運算符在Java中做什麼?
- 30. 在Java中,object.class是做什麼的?
有沒有嘗試只有做 – 2010-04-07 02:20:00
以前沒有問過這個問題嗎?哦,不要忘了谷歌 – 2010-04-07 03:34:17
嗯,做和(!做)。 – MJB 2010-04-08 20:47:53