为了简化“受检查异常”的处理工作,可以将其包装成为“不受检查异常”,这样就不必捕获它,或者在异常声明中列出。注意,这样抛出的异常就是一个新的封装了原受检查异常的异常了。如果程序员确切知道会发生该异常,则可以对其进行捕获,并利用getCause()获取原“受检查异常”并再对其进行处理。再次捕获进catch块中的时候,编译器强制用Throwable作为“保底”
//IgnoreRuntimeException.java
//Transform a compile-checked exception into a Runtime Exception
package com.msn.spaces.bryantd001;
class CheckedWhenCompliedException extends Exception{
private String str;
CheckedWhenCompliedException(){
super("Compile-checked Exception");
str = "Compile-checked Exception --> Runtime Exception";
}
public void throwRuntimeException(){
System.out.println("I will be transformed into a Runtime Exception and be rethrown.");
throw new RuntimeException(this);
}
public String toString(){
return str;
}
}
public class IgnoreRuntimeException{
public static void main(String[] args){
try{
CheckedWhenCompliedException e = new CheckedWhenCompliedException();
e.throwRuntimeException();
}catch(RuntimeException re){
try{
throw re.getCause();
}catch(CheckedWhenCompliedException e){
System.out.println(e);
}catch(Throwable e){ //编译器强制异常基类
System.out.println(e);
}
}
}
}