Throw try catch finally in compiling

Throw an exception positively

1
2
3
4
void noZero(int i) throws Exception {
if(i == 0)
throw new Exception("no zero");
}

javap

1
2
3
4
5
6
7
8
9
10
11
12
13
14
void noZero(int) throws java.lang.Exception;
Code:
0: iload_1
1: ifne 14
// class java/lang/Exception
4: new #2
7: dup
// String no zero
8: ldc #3
// Method java/lang/Exception.
//"<init>":(Ljava/lang/String;)V
10: invokespecial #4
13: athrow
14: return

  1. if not equals pass the throw part
  2. if equals take constant string as param create a Exception.
  3. throw it to the caller[handler?].

Catch an exception

1
2
3
4
5
6
7
void e() {
try {
noZero(0);
} catch(ExcpA a) {}
catch(ExcpB b) {}
catch(Exception e) {}
}

javap

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
void e();
Code:
0: aload_0
1: iconst_0
// Method noZero:(I)V
2: invokevirtual #5
5: goto 17
8: astore_1
9: goto 17
12: astore_1
13: goto 17
16: astore_1
17: return
Exception table:
from to target type
0 5 8 Class HaveATry$ExcpA
0 5 12 Class HaveATry$ExcpB
0 5 16 Class java/lang/Exception

excption table
Every catcher have a chance to catch.

astore_1
Beginning of handler for excpSentry() store thrown value in local var 1.

Finally

1
2
3
4
5
6
7
8
9
int f() {
try { noZero(0); }
catch(Exception e) {
return 1;
}
finally {
return 2;
}
}

javap

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
int f();
Code:
0: aload_0
1: iconst_0
// Method noZero:(I)V
2: invokevirtual #5
5: iconst_2
6: ireturn
7: astore_1
8: iconst_1
9: istore_2
10: iconst_2
11: ireturn
12: astore_3
13: iconst_2
14: ireturn
Exception table:
from to target type
0 5 7 Class java/lang/Exception
0 5 12 any
7 10 12 any

5/6 copy instructions of 13/14.
7th is the Exception handler.
11th can’t reach.
what’s the object of istore_2/ istore_3 ???

istore_2 the catcher itself’s handler?
istore_3 the finaly’s handler comes from istore_2 ?

any mean in range instructions finished then goto target.

The final return handle by finally got 2