考虑到这一点的代码,我可以绝对肯定的是,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) 我们可以在finally块中使用return语句.这会导致任何问题吗?
public class Test2 {
public static void main(String[] args) {
Test2 obj=new Test2();
String a=obj.go();
System.out.print(a);
}
public String go() {
String q="hii";
try {
return q;
}
finally {
q="hello";
System.out.println("finally value of q is "+q);
}
}
Run Code Online (Sandbox Code Playgroud)
为什么hii从函数返回后打印go(),在finally块中值已更改为"hello"?
该计划的输出是
finally value of q is hello
hii
Run Code Online (Sandbox Code Playgroud) 试试这段代码.为什么getValueB()返回1而不是2?毕竟,increment()函数被调用两次.
public class ReturningFromFinally
{
public static int getValueA() // This returns 2 as expected
{
try { return 1; }
finally { return 2; }
}
public static int getValueB() // I expect this to return 2, but it returns 1
{
try { return increment(); }
finally { increment(); }
}
static int counter = 0;
static int increment()
{
counter ++;
return counter;
}
public static void main(String[] args)
{
System.out.println(getValueA()); // prints 2 as expected
System.out.println(getValueB()); …Run Code Online (Sandbox Code Playgroud) 我有以下代码
public static void nocatch()
{
try
{
throw new Exception();
}
finally
{
}
}
Run Code Online (Sandbox Code Playgroud)
这给出了错误
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unhandled exception type CustomException
Run Code Online (Sandbox Code Playgroud)
这是预期的,但return在finally块中添加语句会使错误消失
public static void nocatch()
{
try
{
throw new Exception();
}
finally
{
return; //makes the error go away!
}
}
Run Code Online (Sandbox Code Playgroud)
有人可以解释一下发生了什么事吗?为什么错误会消失?
注意:我编写此代码纯粹是为了实验目的!
java exception-handling exception try-catch try-catch-finally
作为一项规则,该finally块总是执行中的异常是否被抛出try块或continue,break或return在声明中遭遇try块本身.
因此,应该更改下面给出的代码片段中的方法的返回值,但不会.
final class Product
{
private String productName=null;
public Product(String productName)
{
this.productName=productName;
}
public String getProductName()
{
try
{
return this.productName;
}
finally
{
this.productName="The product name has been modified in the finally block.";
System.out.println("Product name in the finally block : "+this.productName);
}
}
}
public final class Test
{
public static void main(String...args)
{
System.out.println(new Product("Intel core i3").getProductName());
}
}
Run Code Online (Sandbox Code Playgroud)
在调用此方法之前,该方法getProductName()只返回由构造函数指定给字段的产品名称productName. …