本文主要是介绍深入拆解 Java 虚拟机 】Exception异常笔记,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
【深入拆解 Java 虚拟机 】Exception异常笔记
- try-with-resource语法糖
- finally
try-with-resource语法糖
try后对象的close方法都会被运行。
package com.exception.demo;
public class Foo implements AutoCloseable {private final String name;public Foo(String name) { this.name = name; }@Overridepublic void close() {System.out.println(name);}public static void main(String[] args) {try (Foo foo0 = new Foo("Foo0"); // try-with-resourcesFoo foo1 = new Foo("Foo1");Foo foo2 = new Foo("Foo2")) {System.out.println("ssssss");try {Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("22222");throw new RuntimeException("Initial");}}
}
start
end
Foo2
Foo1
Foo0
Exception in thread "main" java.lang.RuntimeException: Initialat com.exception.demo.Foo.main(Foo.java:22)
finally
public class Foo2 {private int tryBlock;private int catchBlock;private int finallyBlock;private int methodExit;public void test() {for (int i = 0; i < 100; i++) {try {tryBlock = 0;if (i < 50) {continue;} else if (i < 80) {break;} else {return;}} catch (Exception e) {catchBlock = 1;} finally {finallyBlock = 2;}}methodExit = 3;}
}
对应生成的字节码为
public class com.exception.demo.Foo2 {public com.exception.demo.Foo2();Code:0: aload_01: invokespecial #1 // Method java/lang/Object."<init>":()V4: returnpublic void test();Code:0: iconst_01: istore_12: iload_13: bipush 1005: if_icmpge 758: aload_09: iconst_010: putfield #2 // Field tryBlock:I13: iload_114: bipush 5016: if_icmpge 2719: aload_020: iconst_221: putfield #3 // Field finallyBlock:I24: goto 6927: iload_128: bipush 8030: if_icmpge 4133: aload_034: iconst_235: putfield #3 // Field finallyBlock:I38: goto 7541: aload_042: iconst_243: putfield #3 // Field finallyBlock:I46: return47: astore_248: aload_049: iconst_150: putfield #5 // Field catchBlock:I53: aload_054: iconst_255: putfield #3 // Field finallyBlock:I58: goto 6961: astore_362: aload_063: iconst_264: putfield #3 // Field finallyBlock:I67: aload_368: athrow69: iinc 1, 172: goto 275: aload_076: iconst_377: putfield #6 // Field methodExit:I80: returnException table:from to target type8 19 47 Class java/lang/Exception27 33 47 Class java/lang/Exception8 19 61 any27 33 61 any47 53 61 any61 62 61 any
}
finally在try、catch后都会运行一次,如果内部还有if等多个分支,那么还会赋值运行多次。
这篇关于深入拆解 Java 虚拟机 】Exception异常笔记的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!