Java异常(易错+分析)

2017-09-28  本文已影响0人  Firmbelief

1.

写出程序结果:

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");

}

}

【答案】

//编译失败。 因为打印“A”的输出语句执行不到。

throw单独存在,下面不要定义语句,因为执行不到。

2.

写出程序结果

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.写出程序结果

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("进入方法A");

throw new RuntimeException("制造异常");

} finally {

System.out.println("用A方法的finally");

}

}

static int methodB() {

try {

System.out.println("进入方法B");

// throw new Exception();

return 1;

} catch (Exception e) {

return 3;

} finally {

System.out.println("调用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);

}

}

【答案】

进入方法A

用A方法的finally

制造异常

进入方法B

调用B方法的finally

1

上一篇下一篇

猜你喜欢

热点阅读