我期望以下代码在设置静态变量值的语句之前打印行,但它没有按预期工作。
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();
}
}
}
输出抛出异常“银行处于危机中”,但它应该首先打印一些行“收集现金...”消息,然后抛出异常消息...
最佳答案
问题是你的PrintWriter
永远不会被刷新。它正在积累数据,但它永远不会将其写入控制台,因为在缓冲区已满之前抛出异常。
如果您在引发异常的调用之前调用 writer.flush()
,您将看到预期的消息。
如果您在finally block 中关闭编写器,您将在关闭时看到数据,因为这也会刷新编写器...但是在异常之后,如catch
在 finally
之前执行。
如果您使用 try-with-resources
block ,您将看到异常之前的数据,因为close
有效地发生在“嵌套”尝试/最终中:
try (PrintWriter writer = new PrintWriter(System.out)) {
Bank hsbc = new Bank();
...
} catch(Exception e){
// writer will already be closed here
e.printStackTrace();
}
关于java - java字节码不是顺序执行的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18727703/