1:return 与 finally,下面的代码在finally块中加注释与不加注释两种情况分别输出什么呢,为什么你知道吗?
public class Main {
public static void main(String[] args) throws Exception {
System.out.println(Main.xxx());
}
public static int xxx() {
int i = 0;
try {
return i;
} finally {
i = 1;
//return i;
}
}
}
在注释的情况下是 0 不注释的情况下 输出的是 1
2:
public class Main {
public static void main(String[] args) throws Exception {
System.out.println(Main.xxx());
}
public static Long xxx() {
Long i = new Long(999999);
try {
return i;
} finally {
i=i+2;
}
}
}
输出 999999
3:
public class Main {
public static void main(String[] args) throws Exception {
System.out.println(Main.xxx());
}
public static HashMap<String,String> xxx() {
HashMap<String,String> i = new HashMap<String,String>();
try {
i.put("1", "1");
return i;
} finally {
i.put("2", "2");
//return i;
}
}
}
输出[[1,1],[2,2]]
4:下面代码,在注释与不注释 x.setDaemon(true) 的情况下,分别输出什么?
public static void main(String[] args) throws Exception {
Thread x = new Thread() {
public void run() {
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
} finally {
System.out.println("finally");
}
}
};
x.setDaemon(true);
x.start();
TimeUnit.SECONDS.sleep(2);
}
}
在注释的情况下是 finallly; 不注释的情况下什么也不输出
5.是否可以捕获子线程抛出的异常呢,看下面代码?
public class Main {
public static void main(String[] args) throws Exception {
Thread x = new Thread() {
public void run() {
throw new RuntimeException();
}
};
try {
x.start();
} catch (Exception e) {
System.out.println("got Exception");
}
}
}
上述代码是不会输出 got Exception的,你做对了没有?