Java 绕过编译器检查抛出“受检查的”异常
个别特殊情况下,我们可能想抛出受检查的异常但却并不想在方法上加入throws XXException的signature
比如下面的代码不能成功编译:
public static void main(String[] args){throw new Exception();}
public static void main(String[] args) throws Exception {throw new Exception();}
UNSAFE.throwException(t);
public class ThrowUtil {public static void main(String[] args) {ThrowUtil.<RuntimeException>throwException0(new Exception());}@SuppressWarnings("unchecked")public static <E extends Throwable> void throwException0(Throwable t) throws E {throw (E) t;}}
throw (E) t; // 运行期间不变成了throw (RuntimeException) t了吗?这是要ClassCastException的节奏啊
private static <E extends java/lang/Throwable> void throwException0(java.lang.Throwable) throws E; flags: ACC_PRIVATE, ACC_STATIC Code: stack=1, locals=1, args_size=1 0: aload_0 1: athrow// 注意在athrow之前并没有checkcast指令 LineNumberTable: line 294: 0 LocalVariableTable: StartLengthSlotNameSignature 020tLjava/lang/Throwable; Exceptions: throws java.lang.Throwable// athrow的类型是java.lang.Throwable Signature: #271// <E:Ljava/lang/Throwable;>(Ljava/lang/Throwable;)V^TE;