第三十七题:极端不可思议
public static void main(String[] args) {
try {
System.out.println("Hello world");
} catch (IOException e) {
System.out.println("I've never seen println failed");
}
}
程序不能通过编译,IOException是一个被检查异常,try块内没有引发异常的种子,会编译报错。
public static void main(String[] args) {
try {
//say nothing
} catch (Exception e) {
System.out.println("This can't happen");
}
}
这个程序与上个不同的地方是Exception,这是所有异常的父类,使用catch捕获Exception或Throwable(Exception的父类)是合法的,尽管没有引发异常的种子。
interface type1{
void f() throws CloneNotSupportedException;
}
interface type2{
void f() throws InterruptedException;
}
interface type3 extends type1,type2{
}
public class Arcane3 implements type3{
public static void main(String[] args) {
type3 t3 = new Arcane3();
t3.f();
}
public void f() {
System.out.println("Hello world");
}
}
//控制台打印:
//Hello world
type3接口继承type1和type2,它也就继承f方法,type3内f方法可以抛出的异常是方法所有声明的异常的交集。
第三十八题:不受欢迎的宾客
public class UnwelcomeGuest {
public static final long GUEST_USER_ID = -1;
private static final long USER_ID;
static {
try {
USER_ID = getUserIdFromEnvironment();
} catch (IdUnavailableException e) {
USER_ID = GUEST_USER_ID;
System.out.println("logging in as guest");
}
}
private static long getUserIdFromEnvironment() throws IdUnavailableException{
throw new IdUnavailableException();
}
public static void main(String[] args) {
System.out.println("User ID : " + USER_ID);
}
}
class IdUnavailableException extends Exception{
}
编译报错,USER_ID是一个final变量,必须要初始化。在static代码块中,使用try-catch对USER_ID进行了赋值,但是编译器不能确定是否能对USER_ID这个空final是否赋值成功,保守起见,会报错。
第三十九题:您好,再见!
public static void main(String[] args) {
try {
System.out.println("Hello world");
System.exit(0);
} finally {
System.out.println("Goodbye world");
}
}
finally块会在try块结束后一定执行,但是在这个程序中,try块没有结束其执行过程,System.exit(0)是停止所有程序线程,finnaly没有权限让线程继续执行。
第四十题:不情愿的构造器
public class Reluctant {
private Reluctant internalInstance = new Reluctant();
public Reluctant() throws Exception{
throw new Exception("I'm not coming out");
}
public static void main(String[] args) {
try {
Reluctant b = new Reluctant();
System.out.println("Suprised");
} catch (Exception e) {
System.out.println("I told you so");
}
}
}
程序抛出StackOverflowError异常,本程序包含一个无限递归,internalInstance变量的实例化调用了构造器,而构造器又要先初始化internalInstance变量,循环如此,构成无限的递归,造成异常。StackOverflowError是Error的子类,而不是Exception的,catch无法捕获。