Tag: 最后

在finally块中为null赋值null

以下代码的输出是“Test Passed”; 谁能解释一下为什么? public class Test { public static void main(String args[]) { System.out.println(new Test().print()); } protected StringBuilder print() { StringBuilder builder = new StringBuilder(); try { builder.append(“Test “); return builder.append(“Passed!!!”); } finally { builder = null; } }

最后在exception处理中

exception处理中的finally块究竟执行了什么?

从finally块返回时Java的奇怪行为

试试这段代码。 为什么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(); } } […]

尝试,最后在try块中返回执行流程

尝试时,最后使用组合,如果有返回语句,请尝试。为什么最后是块执行? class Palindrome { public static void main(String args[]) { System.out.println(Palindrome.test()); } public static int test() { try { //return 0; return 100; } finally { System.out.println(“finally trumps return.”); } } } 在上面的代码中,请告诉我执行的流程。 我知道最终将在try块之后强制执行。但是在try块中,返回staatement会将控件带到主类。 在那种情况下,控制将如何最终阻止?

资源是否在最终之前或之后关闭?

在Java 7的try-with-resources中,我不知道finally块和自动关闭发生了哪个顺序。 订单是什么? BaseResource b = new BaseResource(); // not auto-closeable; must be stop’ed try(AdvancedResource a = new AdvancedResource(b)) { } finally { b.stop(); // will this happen before or after a.close()? }

为什么我需要最终使用来关闭资源?

大多数时候,我唯一看到的块块就是这样的 FileInputStream f; try{ f= new FileInputStream(“sample.txt”); //something that uses f and sometimes throws an exception } catch(IOException ex){ /* Handle it somehow */ } finally{ f.close(); } 我的问题是,如果f的范围以封闭块结束,为什么我们需要在finally中关闭它?

在Java中,是否保证要调用“finally”块(在main方法中)?

我是Java新手,我想知道,如果我有以下典型的Java代码 public class MyApp { public static void main(String[] args) { try { // do stuff } catch { // handle errors } finally { // clean up connections etc. } } } JVM是否保证finally块始终运行? 要了解我的来源,我习惯于C / C ++程序,如果取消引用NULL指针,可能会崩溃,之后就无法运行任何代码。 但是由于我理解Java和整个GC /托管内存业务,所以没有空指针解除引用,所有东西都是可捕获的预期,所以我的程序没有真正的崩溃方式可以让它跳过最后,还是在那里? 例如,在Python中,我通常会这样做 try: # do stuff except AnExceptionIKnewMightHappen: # react in an appropriate way except: # […]

java:尝试finally块执行

当存在return;时,我对try-finally执行感到困惑return; 在try块中。 根据我的理解,finally块将始终执行,即在返回调用方法之前。 在考虑以下简单代码时: public class TryCatchTest { public static void main(String[] args){ System.out.println(test()); } static int test(){ int x = 1; try{ return x; } finally{ x = x + 1; } } } 打印的结果实际为1.这是否表示finally块未执行? 任何人都可以帮助我吗?