小米课
返回首页 | 淘宝问答 | 提交答案
关键字: 赤脚医生 优秀典型 理性情绪 情绪疗法 三个阶段 标杆管理 少数民族 省份 | 时间:2024-09-16 07:06

发布时间:2024-09-16 07:06

| 人浏览

【答案】Java习题(第7章)

第七章 1. 答:程序错误主要分3种类型:语法错误,逻辑错误和运行时错误。异常属于运行时错误。

2. 答:在执行方法时,某些语句可能引起异常。也可以使用new明确抛出异常。

3. 答:Java异常一般分为两种类型:运行时异常,如ArithemeticException、NullPointerException等。非运行时异常,如IOException、FileNotFoundException等。

4. 答:捕获异常使用try~catch~finally结构。执行过程是:如果在try块中的代码发生异常,运行时系统将在catch块中寻找匹配的异常,若找到,进入catch块处理,最后执行finally块。

需要注意的问题:

① catch块和finally块不能单独使用,需与try配合使用。

② 一个try可跟多个catch块,多个catch块中的异常应子类异常在前,超类异常在后。

③ 若有finally块,则无论是否发生异常,finally块都将被执行。除非在try块中使用了System.exit()语句。

5. 答:throws用在方法定义时声明抛出异常;throw用于明确抛出异常对象。

6. 答:只有在try块中使用了System.exit()语句时,finally结构中的语句才不被执行。

7. 答:在预定义的异常类不能满足要求时,需要定义自己的异常类。一般是继承Exception类或其子类。

8. 答:A,D,E,F

9. 输出结果为:

The value of i:3

2

The value of i:2

3

The value of i:1

6

The value of i:0

Divided by zero.

10. 答:G 11. 答:B 12. 答:A

13. 答:A 14. 答:将两个catch块中的异常类名交换。

15. 运行结果为:

output = 13423

16. 写出下列程序的运行结果。

inside methodA

methodA’s finally

Exception caught

inside methodB

methodB’s finally

inside methodC

methodC’s finally

17. 当输入数据不是字符串时将抛出InputMismatchException异常,程序中应对该异常处理,程序如下:

import java.util.*;

public class Test{

public static void main(String args[]){

Scanner sc = new Scanner(System.in);

System.out.print("Input a radius:");

try{

double radius = sc.nextDouble();

double area = Math.PI*radius*radius;

System.out.printf("area = %.2f%n",area);

}catch(InputMismatchException e){

System.out.println(e);

System.out.println("Number Format Error.");

}

}

}

18. 参考程序如下:

public class Test{

public static void main(String args[]){

try{

throw new Exception("demo exception");

}catch(Exception e){

System.out.println(e.getMessage());

}finally{

System.out.println("Program finished.");

}

}

}

19. 参考程序如下:

public class Test{

public static void methodA() throws IOException{

System.out.println("In method A");

}

public static void methodB(){

methodA();

System.out.println("In method B");

}

public static void main(String args[]){

methodB();

}

}

20. 参考程序如下:

public class MyException extends Exception{

public MyException() {

}

public MyException(String message){

super(message);

}

public void output(){

System.out.println(getMessage());

}

public static void main(String[] args){

try{

throw new MyException("My Exception.");

}catch(MyException e){

e.output();

System.out.println(e.getMessage());

}

}

}


答案有错

上一篇:电大《程序设计基础》综合练习题(2)

下一篇:暂无

小米课手机端XML联系我们