java字节码是不是按顺序执行?

Zub*_*lam 0 java static-members

我期望下面的代码在设置静态变量值的语句之前打印行,但它没有按预期工作.

import java.io.PrintWriter;
class Bank{
private static boolean isInCrisis = false;
public static boolean getIsInCrisis(){return Bank.isInCrisis;}
public static boolean setIsInCrisis(boolean crisis){
    return Bank.isInCrisis = crisis; 
}
public String getCash() throws Exception{
    if(!Bank.isInCrisis){
        return new String("$100"); 
    }
    else{
        throw new Exception("Bank is in crisis"); 
    }
}
}

public class InstanceObjects{
public static void main(String... st) {
    try{
        Bank hsbc = new Bank();
        PrintWriter writer = new PrintWriter(System.out);
        writer.printf("collect cash: %s\n",hsbc.getCash());
        writer.printf("collect cash: %s\n",hsbc.getCash());
        writer.printf("collect cash: %s\n",hsbc.getCash());
        writer.printf("collect cash: %s\n",hsbc.getCash());
        writer.printf("collect cash: %s\n",hsbc.getCash());
        writer.printf("collect cash: %s\n",hsbc.getCash());
        writer.printf("collect cash: %s\n",hsbc.getCash());
        hsbc.setIsInCrisis(true);
        writer.printf("collect cash: %s\n",hsbc.getCash());            
        writer.close(); 
    }catch(Exception e){
        e.printStackTrace(); 
    }
}
}
Run Code Online (Sandbox Code Playgroud)

输出抛出异常"银行处于危机中",但它应首先打印一些"收取现金..."消息然后抛出异常消息...

Jon*_*eet 5

问题是你PrintWriter永远不会被冲洗.它正在累积数据,但它永远不会将其写入控制台,因为在其缓冲区已满之前会抛出异常.

如果writer.flush()在抛出异常的调用之前调用,您将看到预期的消息.

如果你在finally块中关闭编写器,你将在关闭时看到数据,因为它也会刷新编写器......但是异常之后,就像catch之前执行的那样finally.

如果你使用一个try-with-resources块,你会看到异常之前的数据,因为有close一个"嵌套"的try/finally,有效地发生:

try (PrintWriter writer = new PrintWriter(System.out)) {
    Bank hsbc = new Bank();
    ...
} catch(Exception e){
    // writer will already be closed here
    e.printStackTrace(); 
}
Run Code Online (Sandbox Code Playgroud)