1.
寫出程序結(jié)果:
class Demo{
public static void func(){
try{
throw? new Exception();
System.out.println("A");
}
catch(Exception e){
System.out.println("B");
}
}
public static void main(String[] args){
try{
func();
}
catch(Exception e){
System.out.println("C");
}
System.out.println("D");
}
}
【答案】
//編譯失敗廉嚼。 因?yàn)榇蛴 癆”的輸出語句執(zhí)行不到撩嚼。
throw單獨(dú)存在,下面不要定義語句栅哀,因?yàn)閳?zhí)行不到曙搬。
2.
寫出程序結(jié)果
class Exc0 extends Exception{}
class Exc1 extends Exc0{}
class Demo{
public static void main(String[] args){
try{
throw new Exc1();
}
catch(Exception e){
System.out.println("Exception");
}
catch(Exc0 e){
System.out.println("Exc0");
}
}
}
【答案】
編譯不通過究西!
多個catch時货葬,父類的catch要放在下面个束。
3.寫出程序結(jié)果
class Test{
public static String output="";
public static void foo(int i){
try{
if(i==1)
throw new Exception();
output+="1";
}
catch(Exception e){
output+="2";
//return;
}
finally{
output+="3";
}
output+="4";
}
public static void main(String args[]){
foo(0);
System.out.println(output);//
foo(1);
System.out.println(output);//
}
}
【答案】
//134
//134234
4.
public class ReturnExceptionDemo {
static void methodA() {
try {
System.out.println("進(jìn)入方法A");
throw new RuntimeException("制造異常");
} finally {
System.out.println("用A方法的finally");
}
}
static int methodB() {
try {
System.out.println("進(jìn)入方法B");
// throw new Exception();
return 1;
} catch (Exception e) {
return 3;
} finally {
System.out.println("調(diào)用B方法的finally");
// return 2;
}
}
public static void main(String[] args) {
try {
methodA();
} catch (Exception e) {
System.out.println(e.getMessage());
}
int i = methodB();
System.out.println(i);
}
}
【答案】