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. cipher.update在java中做什么?
- 2. fpstrict在Java中做什么?
- 3. Collections.unmodifiableSet()在Java中做什么?
- 4. 什么是outData.writeInt()在Java中做什么?
- 5. 什么尝试可以在PHP文件中做?
- 6. 微软商业智能。我正在尝试做什么?
- 7. 尝试执行SQL注入攻击 - 他们在做什么?
- 8. 什么下面的语句在执行的尝试做
- 9. 尝试,美中不足的是:做什么,如果TRY成功
- 10. 尝试从SwingWorker done()方法中绘制JPanel什么也不做
- 11. java目前在做什么?
- 12. Java中'0'做什么?
- 13. “做”在这里做什么? (java)
- 14. 在Perl中做什么=〜做什么?
- 15. 在Java中,object.class是做什么的?
- 16. | =运算符在Java中做什么?
- 17. 在Java中做什么<>?
- 18. >>在java中做什么?
- 19. 在Java中File.canExecute()究竟做了什么?
- 20. 这是我正在尝试在MySQL中做什么的最佳查询?
- 21. 在Java中捕获后重做一次尝试
- 22. 我做错了什么?尝试从API获得响应
- 23. 我在这个可串行化尝试中做了什么错误
- 24. 我正在尝试使用Java在Oracle数据库中更新我的密码。难道我做错了什么?
- 25. 测试人员做什么?
- 26. 测试是做什么的?
- 27. Java - “(Customer)v.get(i)”做什么?
- 28. Java类什么都不做
- 29. 单元测试究竟在做什么?
- 30. 这段Java代码在做什么?
有没有尝试只有做 – 2010-04-07 02:20:00
以前没有问过这个问题吗?哦,不要忘了谷歌 – 2010-04-07 03:34:17
嗯,做和(!做)。 – MJB 2010-04-08 20:47:53