考虑到这一点的代码,我可以绝对肯定的是,finally块总是执行,不管something()是什么?
try {
something();
return success;
}
catch (Exception e) {
return failure;
}
finally {
System.out.println("I don't know if this will get printed out");
}
Run Code Online (Sandbox Code Playgroud) 有什么区别
try {
fooBar();
} finally {
barFoo();
}
Run Code Online (Sandbox Code Playgroud)
和
try {
fooBar();
} catch(Throwable throwable) {
barFoo(throwable); // Does something with throwable, logs it, or handles it.
}
Run Code Online (Sandbox Code Playgroud)
我更喜欢第二个版本,因为它让我可以访问Throwable.两种变体之间是否有任何逻辑差异或首选约定?
另外,有没有办法从finally子句访问异常?
我正在阅读关于异常和断言的章节中的Java教科书,并且遇到了这个代码块,我有一个问题.
public boolean searchFor(String file, String word)
throws StreamException
{
Stream input = null;
try {
input = new Stream(file);
while (!input.eof())
if (input.next().equals(word))
return true;
return false; //not found
} finally {
if (input != null)
input.close();
}
}
Run Code Online (Sandbox Code Playgroud)
在下一段中,文本说"该searchFor方法声明它抛出,StreamException以便生成的任何异常在清理后传递给调用代码,包括StreamException调用close所引发的任何异常.
我的印象是,包含一个throws子句允许程序员抛出异常的特定类(或子类),并且当且仅当它或它的一个超类在throws子句中时,才能抛出一个类.但是在这里,有一个throws条款没有throw声明try.那么首先包括该条款有什么意义呢?在代码中的位置会StreamException被捕获?
程序员在没有catch的情况下使用try块
像这样
PersistenceManager pm = PMF.get().getPersistenceManager();
try {
pm.makePersistent(c);
} finally {
pm.close();
}
Run Code Online (Sandbox Code Playgroud)
异常会发生什么以及以后可能会如何处理?
我尝试从互联网上学习,但没有明确的结果......
通常这会给出语法错误.但是在Statement部分的oracle教程中try-with-resources,有几个带有try块但没有catch或finally语句的代码示例.为什么这些代码不会出现语法错误?