考虑到这段代码,我能绝对确定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");
}
考虑到这段代码,我能绝对确定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");
}
当前回答
无论异常处理与否,Finally块始终执行。如果在try块之前发生任何异常,那么Finally块将不会执行。
其他回答
答案很简单:是。
输入:
try{
int divideByZeroException = 5 / 0;
} catch (Exception e){
System.out.println("catch");
return; // also tried with break; in switch-case, got same output
} finally {
System.out.println("finally");
}
输出:
catch
finally
我试过了,它是单线程的。
public static void main(String args[]) throws Exception {
Object obj = new Object();
try {
synchronized (obj) {
obj.wait();
System.out.println("after wait()");
}
} catch (Exception ignored) {
} finally {
System.out.println("finally");
}
}
主线程将永远处于等待状态,因此最终不会被调用,
因此控制台输出不会在wait()或finally之后打印String:
同意@Stephen C的观点,上述示例是这里提到的第三个案例之一:
在以下代码中添加更多这样的无限循环可能性:
// import java.util.concurrent.Semaphore;
public static void main(String[] args) {
try {
// Thread.sleep(Long.MAX_VALUE);
// Thread.currentThread().join();
// new Semaphore(0).acquire();
// while (true){}
System.out.println("after sleep join semaphore exit infinite while loop");
} catch (Exception ignored) {
} finally {
System.out.println("finally");
}
}
案例2:如果JVM首先崩溃
import sun.misc.Unsafe;
import java.lang.reflect.Field;
public static void main(String args[]) {
try {
unsafeMethod();
//Runtime.getRuntime().halt(123);
System.out.println("After Jvm Crash!");
} catch (Exception e) {
} finally {
System.out.println("finally");
}
}
private static void unsafeMethod() throws NoSuchFieldException, IllegalAccessException {
Field f = Unsafe.class.getDeclaredField("theUnsafe");
f.setAccessible(true);
Unsafe unsafe = (Unsafe) f.get(null);
unsafe.putAddress(0, 0);
}
参考:如何使JVM崩溃?
情况6:如果finally块将由守护程序线程执行,并且所有其他非守护程序线程在finally被调用之前退出。
public static void main(String args[]) {
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
printThreads("Daemon Thread printing");
// just to ensure this thread will live longer than main thread
Thread.sleep(10000);
} catch (Exception e) {
} finally {
System.out.println("finally");
}
}
};
Thread daemonThread = new Thread(runnable);
daemonThread.setDaemon(Boolean.TRUE);
daemonThread.setName("My Daemon Thread");
daemonThread.start();
printThreads("main Thread Printing");
}
private static synchronized void printThreads(String str) {
System.out.println(str);
int threadCount = 0;
Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
for (Thread t : threadSet) {
if (t.getThreadGroup() == Thread.currentThread().getThreadGroup()) {
System.out.println("Thread :" + t + ":" + "state:" + t.getState());
++threadCount;
}
}
System.out.println("Thread count started by Main thread:" + threadCount);
System.out.println("-------------------------------------------------");
}
输出:这不会打印“finally”,这意味着“守护进程线程”中的“finally块”没有执行
主螺纹打印线程:线程[My Daemon线程,5,main]:状态:BLOCKED线程:线程[main,5,main]:状态:RUNNABLE线程:线程[Monitor Ctrl-Break,5,main]:状态:RUNNABLE主线程启动的线程计数:3------------------------------------------------- Daemon线程打印线程:线程[My Daemon线程,5,main]:状态:RUNNABLE线程:线程[Monitor Ctrl-Break,5,main]:状态:RUNNABLE主线程启动的线程计数:2------------------------------------------------- 进程已完成,退出代码为0
在两种独特的情况下,返回后不会调用finally块:如果首先调用System.exit(),或者JVM崩溃。
让我尽量用最简单的方式回答你的问题。
规则1:finally块始终运行(虽然有例外。但让我们坚持一段时间。)
规则2:当控件离开try或catch块时,finally块中的语句会运行。控制权的转移可能是正常执行、break、continue、goto或return语句的执行或异常传播的结果。
在返回语句的情况下(由于其标题),控件必须离开调用方法,因此调用相应try finally结构的finally块。return语句在finally块之后执行。
如果finally块中也有return语句,它肯定会覆盖try块中挂起的语句,因为它会清除调用堆栈。
您可以在此处找到更好的解释:http://msdn.microsoft.com/en-us/....这一概念在所有高级语言中基本相同。
即使在try块中放入return语句,也始终执行finally块。finally块将在return语句之前执行。
这是因为您将i的值指定为12,但没有将i的返回给函数。正确的代码如下:
public static int test() {
int i = 0;
try {
return i;
} finally {
i = 12;
System.out.println("finally trumps return.");
return i;
}
}