JAVA基础 第6章异常处理机制_练习题_200910

合集下载

java异常处理试题及参考答案

java异常处理试题及参考答案

异常处理练习题一、选择题1.java中用来抛出异常的关键字是(C)A、tryB、catchC、throwD、finally2.关于异常,下列说法正确的是(A)A、异常是一种对象B、一旦程序运行,异常将被创建C、为了保证程序运行速度,要尽量避免异常控制D、以上说法都丌对3.(A)类是所有异常类的父类。

A、4.javaA、try{C、5.{{“除0}A、程序将输出第15行的异常信息B、程序第10行出错C、程序将输出“b=42”D、程序将输出第15和19行的异常信息6.下列程序的执行,说法正确的是(D)class ExMulti{static void procedure(){try{int c[]={1};c[42]=99;}catch(ArrayIndexOutOfBoundsException e){“数组超越界限异常:”+e);}}public static void main(String args[]){“除0}ABCD7.{{}{try{procedure();}catch(IllegalAccessExcepton e) ___________{“捕获:”+e);}}8.对于catch子句的排列,下列哪种是正确的(B )A、父类在先,子类在后B、子类在先,父类在后C、有继承关系的异常不能在同一个try程序段内D、先有子类,其他如何排列都无关9.在异常处理中,如释放资源、关闭文件、关闭数据库等由(C )来完成。

A、try子句B、catch子句C、finally子句D、throw子句10.当方法遇到异常又不知如何处理时,下列哪种说法是正确的(C )A、捕获异常B、抛出异常C、声明异常D、嵌套异常11.哪个关键字可以抛出异常?(C)JVM. int i=0;String greetings[]= {“Hello world!”,“No,I mean it!”,“HELLO WORLD!!”};while(i<4){____try________{}____catch__(ArrayIndexOutOfBoundsException e){i=-1;}finally{}i++;}}三、判断题1. ( F )程序中抛出异常时(throw …),只能抛出自己定义的异常对象。

JAVA第六章习题

JAVA第六章习题

第六章异常和异常处理一、选择题1、下列关于异常和异常类的描述中,错误的是 D 。

A.异常是某种异常类的对象B.异常类代表一种异常事件C.异常对象中包含有发生异常事件的类型等重要信息D.对待异常的处理就是简单地结束程序2、下列关于异常处理的描述中,错误的是 C 。

A.程序运行时出现的异常是通过系统默认的异常处理程序进行处理的。

B.在程序中可以使用try-catch语句捕捉异常和处理异常事件C.对于捕获的异常只能在当前方法中处理D.使用throw语句可将异常抛出到调用当前方法的方法中处理二、简答题1、简述Java的异常处理机制。

Java系统中定义一些用来处理异常的类,称为异常类,该类中通常包含产生某种异常的信息和处理异常的方法等内容。

当程序运行中发生了可识别的异常时(该错误有一个异常类与之相对应时)系统就会产生一个相应的该异常类的对象,简称异常。

系统中一旦产生了一个异常,便去寻找处理该种异常的处理程序,以保证不产生死机,从而保证了程序的安全运行。

这就是Java的异常处理机制.三、写出运行结果题1、public class Exam6_4{ public static void main(String args[]){ fun(0);fun(1);fun(2);fun(3);}static void fun(int i){ System.out.println("调用方法:fun"+i);try{if(i==0) System.out.println("没有异常");else if(i==1){int a=0; int b=10; b/=a;}else if(i==2){int m[]=new int[5]; m[5]=100;}else if(i==3){String str="56k9"; intn=Integer.parseInt(str);}}catch(ArithmeticException e){System.out.println("捕捉异常:"+e.getMessage());} catch(ArrayIndexOutOfBoundsException e){System.out.println("捕捉异常:"+e);}catch(NumberFormatException e){System.out.println("捕捉异常:"+e);}finally{System.out.println("处理完毕! ");}}}2、public class Exam6_5{ public static void main(String args[]){ try{fun1();}catch(ArithmeticException e){System.out.println("捕捉异常:"+e.getMessage());} try{fun2( );}catch(ArrayIndexOutOfBoundsException e){System.out.println("捕捉异常:"+e);}finally {System.out.println("处理完毕! ");}}static void fun1() throws ArithmeticException{ System.out.println("调用方法:fun1");int a=0; int b=10; b/=a;throw new ArithmeticException();}static void fun2() throws ArrayIndexOutOfBoundsException { System.out.println("调用方法:fun2");int m[]=new int[5]; m[5]=100;throw new ArrayIndexOutOfBoundsException();}}。

java考试题库第六章.docx

java考试题库第六章.docx

第六章异常和异常处理一选择题6・1 .下列关于异常的描述中,错误的是(B)A.异常是一种经过修正后程序仍可执行的错误B.异常是一种程序在运行中出现的不可恢复执行的错误C.不仅Java语言有异常处理,C++语言也有异常处理D.岀现异常不是简单结束程序,而是执行某种处理异常的代码,设法恢复程序的执行6・2.下列关于异常处理的描述中,错误的是(D)A.程序运行时异常由Java虚拟机自动进行处理B.使用try-catch-finally语句捕获异常C.使用throw语句抛出异常D.捕获到的异常只能用当前方法中处理,不能用其他方法中处理6・3.下列关于try-catch-finally语句的描述中,错误的是(A)A・try语句后面的程序段将给出处理异常的语句B・catch ()方法跟在try语句后面,它可以是一个或多个C. catch ()方法有一个参数,该参数是某种异常类的对彖D・finally语句后面的程序段总是被执行的,该语句起到提供统一接口的作用6・4.下列关于抛出异常的描述中,错误的是(D)A.捕捉到发牛的异常可在当前方法中处理,也可以抛到调用该方法的方法中处理B.在说明要抛出异常的方法吋应加关键字throw<异常列表〉C.v异常列表〉中可以有多个用逗号分隔的异常D.抛岀异常的方法中要使用下述抛出异常语句:throw<异常名〉;其中,v异常名>是异常类的类名6・5.下列关于用户创建自己的异常描述中,错误的是(D)A.创建自己的异常应先创建一个异常类B.为实现抛出异常,须在可能抛出异常的方法中书写throw语句C.捕捉异常的方法是使用try-catch-finally语句格式D.使用异常处理不会使整个系统更加安全和稳定二判断题6・1 .异常是一种特殊的运行错误的对象。

(对)62异常处理可以使整个系统更加安全和稳定。

(对)6・3.异常处理是在编译时进行的。

(错)6-4.Java语言中异常类都是ng.Throwable的子类。

java异常处理练习题

java异常处理练习题

java异常处理练习题Java异常处理练习题Java是一种面向对象的编程语言,广泛应用于软件开发领域。

在Java编程中,异常处理是一个非常重要的概念。

通过合理处理异常,我们可以提高程序的可靠性和健壮性。

本文将介绍一些Java异常处理的练习题,帮助读者更好地理解和掌握异常处理的知识。

1. 编写一个程序,从命令行获取一个整数,并将其平方输出。

如果输入的不是整数,则抛出一个自定义的异常"InvalidInputException",并提示用户重新输入。

```javaimport java.util.Scanner;class InvalidInputException extends Exception {public InvalidInputException(String message) {super(message);}}public class SquareNumber {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);try {System.out.print("请输入一个整数: ");int num = scanner.nextInt();System.out.println("平方结果: " + num * num);} catch (Exception e) {scanner.nextLine(); // 清除输入缓冲区System.out.println("输入无效,请重新输入。

");main(args); // 递归调用自身,重新执行程序}}}```2. 编写一个方法,接收一个整数数组和一个整数n作为参数,返回数组中第n 个元素的值。

如果n超出数组的索引范围,则抛出一个自定义的异常"ArrayIndexOutOfBoundException",并提示用户重新输入。

java语言程序设计第6章

java语言程序设计第6章
同父类的异常统一处理,也可区分不同的异常分别处理,使用非常灵活。
第6章 常见错误和异常处理
6.2.2 Exception类
Java语言的异常类是处理运行时错误的特殊类,每一种异常类对应一种特定 的运行错误。所有的Java异常类都是系统类库中的Exception类的子类 。 Exception类有若干子类,每一个子类代表了一种特定的运行时错误。这些 子类有些是系统事先定义好并包含在Java类库中的,称为系统定义的运行异 常。 系统定义的运行异常通常对应着系统运行错误。由于这种错误可能导致操作 系统错误甚至是整个系统的瘫痪,所以需要定义异常类来特别处理。 常见的系统定义异常如下: (1)ArithmeticException:数学错误。 (2)ArrayIndexOutOfBoundsException:数组下标越界使用。 (3)ClassNotFoundException:未找到欲使用的类。 (4)FileNotFoundException:未找到指定的文件或目录。
第6章 常见错误和异常处理
6.2.4 多异常的处理
如果所有的catch语句都不能与当前的异常对象匹配,则说明当前方法不能 处理这个异常对象,程序流程将返回到调用该方法的上层方法。如果这个上 层方法中定义了与所产生的异常对象相匹配的catch语句,流程就跳转到这 个catch语句中,否则将继续回溯更上层的方法。 如果所有的方法中都找不到合适的catch语句,则由Java运行系统来处理这 个异常对象。此时通常会中止程序的执行,退出虚拟机返回操作系统,并在 标准输出上打印相关的异常信息。 如果try语句体中所有语句的执行都没有引发异常,则所有的catch语句体都 会被忽略而不予执行。 catch语句体中的语句应根据异常的不同而执行不同的操作,比较通用的操 作是打印异常和错误的相关信息,包括异常名称、产生异常的方法名等。 由于异常对象与catch语句的匹配是按照catch语句的先后排列顺序进行的, 所以在处理多异常时应注意认真设计各catch语句的排列顺序。一般来说, 将处理较具体和较常见的异常的catch语句应放在前面,而可以与多种异常 相匹配的catch语句应放在较后的位置。此外,不能将子类异常的catch语句 放在父类的后面,否则在编译时会产生错误。

AnjoyoJava06章节考试题

AnjoyoJava06章节考试题

第六章考试题一、选择题:(每题3分,共20题)1.关于异常的含义,下列描述中最正确的一项是()。

A、程序编译或运行时发生的异常事件B、程序语法错误C、程序自定义的异常事件D、程序编译错误2.自定义异常时,可以通过对下列哪一项进行继承(A )。

A、Exception类及其子类B、Applet类C、AssertionError类D、Error类3.对应try和catch子句的排列方式,下列说法正确的一项是(B )。

A、父类和子类不能同时出现在try语句块中B、子类异常在前,父类异常在后C、父类异常在前,子类异常在后D、只能有子类异常4.运行下面程序时,会产生的异常是( D )。

public class Test06_01 {public static void main(String[] args) {int x = 0;int y = 5/x;int[] z = {1,2,3,4};int p = z[4];}}A、ArrayIndexOutOfBoundsExceptionB、IOExceptionC、NumberFormatExceptionD、ArithmeticException5.运行下面程序时,会产生的异常是(D)。

public class Test06_02 {public static void main(String[] args) {int[] z = {1,2,3,4};int p = z[4];int x = 0;int y = 5/x;}}A、NumberFormatExceptionB、ArithmeticExceptionC、IOExceptionD、ArrayIndexOutOfBoundsException6.下列程序执行的结果是()。

public class Test06_03 {public static void main(String[] args) {try{return;}finally{System.out.println("Finally");}}}A、编译通过,但运行时出现异常B、因为没有catch子句,因此不能通过编译C、程序正常运行,并输出FinallyD、程序正常运行,但不输出任何结果7.下列代码中给出正确的在方法体内抛出异常的是()。

《Java语言程序设计:基础篇》课后复习题答案-第六章

《Java语言程序设计:基础篇》课后复习题答案-第六章

《Java语言程序设计:基础篇》课后复习题答案-第六章Chapter6Single-dimensional Arrays1.See the section"Declaring and Creating Arrays."2.You access an array using its index.3.No memory is allocated when an array is declared.The memory is allocated whencreating the array.x is60The size of numbers is304.Indicate true or false for the following statements:1.Every element in an array has the same type.Answer:True2.The array size is fixed after it is declared.Answer:False3.The array size is fixed after it is created.Answer:True4.The element in the array must be of primitive data type.Answer:False5.Which of the following statements are valid array declarations?int i=new int(30);Answer:Invaliddouble d[]=new double[30];Answer:Validchar[]r=new char(1..30);Answer:Invalidint i[]=(3,4,3,2);Answer:Invalidfloat f[]={2.3, 4.5, 5.6};Answer:Validchar[]c=new char();Answer:Invalid6.The array index type is int and its lowest index is0.a[2]7.(a)double[]list=new double[10];(b)list[list.length–1]=5.5;(c)System.out.println(list[0]+list[1]);(d)double sum=0;for(int i=0;i<list.length;i++)< p="">sum+=list[i];(e)double min=list[0];for(int i=1;i<list.length;i++)< p="">if(min>list[i])min=list[i];(f)System.out.println(list[(int)(Math.random()*list.length));(g)double[]={3.5, 5.5, 4.52, 5.6};8.A runtime exception occurs.9.Line3:the array declaration is wrong.It should be double[].The array needs tobe created before its been used.e.g.new double[10]Line5:The semicolon(;)at the end of the for loop heading should be removed.Line5:r.length()should be r.length.Line6:random should be random()Line6:r(i)should be r[i].10.System.arraycopy(source,0,t,0,source.length);11.The second assignment statement myList=new int[20]creates a new array andassigns its reference to myList.myList new int[10]Array myList new int[10]Arraynew int[20]Array12.False.When an array is passed to a method,the reference value of the array ispassed.No new array is created.Both argument and parameter point to the samearray.13.numbers is 0and numbers[0]is314.(A) ExecutingcreateArray in Line 6Space required for the main methodchar[] chars: refHeap Array of 100 charactersSpace required for the createArray methodchar[] chars: ref(B) After exitingcreateArray in Line 6Space required for themain methodchar[] chars: refHeapArray of 100charactersStack Stack (C) ExecutingdisplayArray in Line 10Space required for the main methodchar[] chars: refHeap Array of 100 charactersSpace required for the displayArray method char[] chars: ref(D) After exitingdisplayArray in Line10Space required for themain methodchar[] chars: refHeapArray of 100charactersStack Stack(E) Executing countLetters in Line 13 Space required for the main methodint[] counts: refchar[] chars: refHeap Array of 100 charactersSpace required for the countLetters method int[] counts: refchar[] chars: ref (F) After exitingcountLetters in Line 13Space required for themain methodint[] counts: refchar[] chars: refHeapArray of 100charactersStack StackArray of 26 integers Array of 26 integers(G) Executing displayCounts in Line 18Space required for the main methodint[] counts: refchar[] chars: refHeap Array of 100 charactersSpace required for the displayCounts methodint[] counts: ref (H) After exitingdisplayCounts in Line 18Space required for themain methodint[] counts: refchar[] chars: refHeapArray of 100charactersStack StackArray of 26 integers Array of 26 integers15.Only one variable-length parameter may be specified ina method and this parameter must be the last parameter.The method return type cannot be a variable-length parameter.16.The last oneprintMax(new int[]{1,2,3});is incorrect,because the array must of the double[] type.17.Omitted18.Omitted19.Omitted20Simply change(currentMaxlist[j])21Simply change list[k]>currentElement on Line9tolist[k]<currentelement< p="">22.You can sort an array of any primitive types except boolean.The sort method is void,so it does not return a new array.23.To apply java.util.Arrays.binarySearch(array,key),the array must be sorted in increasing order.24.Line1:list is{2,4,7,10}Line2:list is{7,7,7,7}Line3:list is{7,8,8,7}Line4:list is{7,8,8,7}</currentelement<></list.length;i++)<></list.length;i++)<>。

JAVA练习题(第6章)

JAVA练习题(第6章)

System.out.println(sl.concat(s2));
}
}
Hello World!
请写出该程序的运行结果:
3.写出以下程序的运行结果
public class ChangeStrDemo {
public static void changestr(String str){
str="welcome";
Hello World!
2.阅读以下程序 运行结果是:
import java.io.*;
public class abc {
public static void main(String args[]) {
String sl = "Hello!";
String s2 = new String("World!");
if (cArray[i]>’m’)
sb2.insert(j++,cArray[i]);
sb3.setCharAt(0,’h’);
sb3.setCharAt(6,’m’); System.out.println(sb1);yaorsineeudtyCeeoxhm,uaCrphAetamty(ri?ncpthty)主?w要h是y用?
A. arit
B. arit
C. amit
amit
arit
amit
false
false
false
true
true
true
D. arit amit true true
10.运行以下的main()方法,结果是( )
1. public static void main(String[] args)

java异常处理考试

java异常处理考试

Java异常处理技术一、选择题1.请问所有的异常类皆继承哪一个类?(A)A.ng.Throwable B.ng.ExceptionC.ng.Error D.java.io.Exception2.哪个关键字可以抛出异常?(B)A.transient B.throw C.finally D.catch3.对于已经被定义过可能抛出异常的语句,在编程时(A)。

A.必须使用try/catch语句处理异常,或用throw将其抛出。

B.如果程序错误,必须使用 try/catch语句处理异常。

C.可以置之不理。

D.只能使用try/catch语句处理。

4.下面程序段的执行结果是什么?(B)public class Foo{public static void main(String[] args){try{return;}finally{System.out.println("Finally");}}}A.编译能通过,但运行时会出现一个例外。

B.程序正常运行,并输出 "Finall y"。

C.程序正常运行,但不输出任何结果。

D.因为没有catch语句块,所以不能通过编译。

5.下面是一些异常类的层次关系:ng.Exceptionng.RuntimeExceptionng.IndexOutOfBoundsExceptionng.ArrayIndexOutOfBoundsExceptionng.StringIndexOutOfBoundsException假设有一个方法X,能够抛出两个异常,Array Index和String Index异常,假定方法X中没有try-catch语句处理这些异常,下面哪个答案是正确的?( A B)A.方法X 应该声明抛弃ArrayIndexOutOfBoundsException和StringIndexOutOf Bounds- Exception。

《Java语言程序设计-基础篇》答案-第06章

《Java语言程序设计-基础篇》答案-第06章

第6章 类与对象复习题6.1 答: 略6.2答: 略6.3答: 构造方法 ShowErrors(int) 没有定义.原因是默认的构造函数是没有参数的.6.4答: 略6.5答: 变量c 没有初始化,也可以说是没有将对象引用到实例.即c 为null. 6.6 答: 构造函数A()没有定义.原因是类中有了有参的构造方法A(String s),但没有无参构造方法,而系统不会再提供默认的构造函数A()。

系统找不到默认的构造函数.在这种情况下,如果还要用A(),则需要重新定义. 6.7 答:构造函数C(double)没有定义.原因是默认的构造函数是没有参数的. 6.8 答:输出:false;原因是boolean 类型的变量如果没有初始化,则默认初始值为false; 6.9 答:方法x()没有定义;6.10答:略6.11答:略6.12答:输出:1.0;私有变量可以被类里的成员方法访问.6.13答:略6.14答:略6.15答:传递基本类型参数值的变化不能被带回,而引用类型参数的变化可以带回.输出: count is 101 times is 06.16答:After swap1 : circle1= 1.0 circle2=2.0After swap2 : circle1= 2.0 circle2=1.0课后答案网ww w.kh da w .c om6.17答:a[0]= 1 a[1]= 2 (a)a[0]= 2 a[1]= 1 (b)e1 = 2 e2= 1 (c)t1's i = 2 and j= 1 (d)t2's i = 2 and j= 1第四个值得注意,因为 i 为静态的,因此经过二次实例化后,i 就变成2了。

而j 是没有变的,一直为1。

6.18答:System.out .println(f.i);System.out .println(f.s ); f.imethod(); f.smethod ();System.out .println(Foo.s ); Foo.smethod ();但静态成员最好直接用类访问.像 System.out .println(f.s ); f.smethod ();6.19答:i + j is 23k is 2 j is 06.20答:不能在静态方法中调用非静态方法,不能在静态方法中调用非静态变量.反之可以.错误是:不能调用method1(),不能调用c.6.22答:错误没有,但会提出警告:p 不明确,这里应该用this.p;6.23答:第一个输出为:null,因为一个对象的默认值是null,而第二个输出有错,原因是没有将对象引用到实例,即dates[0]为空课后答案网ww w.kh da w .c om。

JAVA语言程序设计基础课后习题第六章

JAVA语言程序设计基础课后习题第六章

JAVA语⾔程序设计基础课后习题第六章//exercise 6.1package second;import java.util.Scanner;public class first {/*** @param args*/public static void main(String[] args) {// TODO Auto-generated method stubScanner in=new Scanner(System.in);System.out.print("Enter the number of students:");int number=in.nextInt();System.out.print("Enter "+number+" scores:");int []score=new int[number];getscores(score);int best=max(score);for(int i=0;i<number;i++){System.out.println("Student "+i+" score is "+score[i]+" and grade is "+grade(score[i],best));}}public static void getscores(int []score){Scanner in=new Scanner(System.in);for(int i=0;i<score.length;i++){score[i]=in.nextInt();}}public static int max(int[] score){int max=score[0];for(int i=0;i<score.length;i++){if(max<score[i])max=score[i];}return max;}public static char grade(int score,int max){if(score>=max-10)return 'A';else if(score>=max-20)return 'B';else if(score>=max-30)return 'C';else if(score>=max-40)return 'D';elsereturn 'F';}}//exercise 6.2package second;import java.util.Scanner;public class second {/*** @param args*/public static void main(String[] args) {// TODO Auto-generated method stubint []number=get();reverseprint(number);}public static int[] get(){Scanner in=new Scanner(System.in);int[] number=new int[10];System.out.println("input 10 number:");for(int i=0;i<number.length;i++){number[i]=in.nextInt();}return number;}public static void reverseprint(int[]Array){for(int i=Array.length-1;i>=0;i--){System.out.print(Array[i]+" ");}}}//exercise 6.3package second;import java.util.Scanner;public class third {/*** @param args*/public static void main(String[] args) {// TODO Auto-generated method stubScanner in=new Scanner(System.in);int[] newarray=new int[100];int temp;for(int i=0;i<newarray.length;i++){newarray[i]=0;}System.out.print("Enter the integers between 1 and 100:");while((temp=in.nextInt())!=0){newarray[temp]++;}resultprint(newarray);}public static void resultprint(int []array){for(int i=0;i<array.length;i++){if(array[i]==1)System.out.println(i+" occurs "+array[i]+" time");if(array[i]!=0&&array[i]!=1)System.out.println(i+" occurs "+array[i]+" times");}}}//exercise 6-4package first;import java.util.Scanner;public class first {/*** @param args*/public static void main(String[] args) {// TODO Auto-generated method stubScanner in=new Scanner(System.in);int []score=new int[100];int i=0,sum=0,count=0;System.out.print("input integer:");while((score[i]=in.nextInt())!=-1){sum+=score[i++];count++;}int average=sum/count;int big=0,small=0;for(int j=0;j<count;j++){if(score[j]<average)small++;elsebig++;}System.out.println("average is "+average);System.out.println("better than average is "+big);System.out.println("small than average is "+small);}}//exercise 6-5package first;import java.util.Scanner;public class second {/*** @param args*/public static void main(String[] args) {// TODO Auto-generated method stub Scanner in=new Scanner(System.in); System.out.print("Enter ten numbers:");int []integer=new int[10];int count=0;for(int i=0;i<10;i++){boolean judge=false;int temp=in.nextInt();for(int j=0;j<count;j++){if(temp==integer[j]){judge=true;}}if(!judge){integer[count++]=temp;}}System.out.print("input integer:");for(int i=0;i<count;i++){System.out.print(integer[i]+" ");}}}//exercise 6-7package first;public class third {/*** @param args*/public static void main(String[] args) {// TODO Auto-generated method stubint []counts=new int[10];for(int i=0;i<100;i++){int random=(int)(Math.random()*10); counts[random]++;}for(int i=0;i<10;i++){System.out.print(i+" ");}System.out.println();for(int i=0;i<10;i++){System.out.print(counts[i]+" ");}}}//exercise 6-8package first;public class fourth {/*** @param args*/public static int average(int[]array){int sum=0,count=0;for(int i=0;i<array.length;i++){sum+=array[i];count++;}return sum/count;}public static double average(double []array){double sum=0;int count=0;for(int i=0;i<array.length;i++){sum+=array[i];count++;}return sum/count;}}//exercise 6-9package first;public class fifth {/*** @param args*/public static double min(double []array){double min=array[0];for(int i=0;i<array.length;i++){if(min>array[i])min=array[i];}return min;}}//exercise 6-10package first;public class seventh {/*** @param args*/public static int indexOfSmallestElement(double[] array){ double min=array[0];for(int i=0;i<array.length;i++){if(min>array[i])min=array[i];}for(int i=0;i<array.length;i++){if(min==array[i])return i;}return 0;}}。

java第6章

java第6章

• 一个throws子句列举了一个方法可能抛出的 所有异常类型,各个异常类型之间使用逗号分 割。凡是Error或RuntimeException子类的 异常都不需要在异常列表中指定,而其他类型 的异常必须进行指定声明。否则会产生编译时 错误。在使用try…catch语句捕捉某些异常的 同时,还可以使用throws声明不需要在方法 中处理的异常
• 在Java中,任何异常对象都是n g.Throwable类或其子类的对象,即所 有异常类型都是内置类Throwable的 子类。
Throwable
Error
Exception
ClassNotFoundException DataFormatException IOException
第6章 异常处理机制
• 程序的三种错误:
–语法错误:编写代码的过程可能输入的字 符错误,不符合相应的命令格式等。 –运行时错误:程序在运行中出现意料不到 情况,如除数为零,数组越界等。 –逻辑错误:程序的运行结果和我们预想的 结果不一致,这是一种难以调试的错误。
• 在Java语言中,异常又称为例外,是运 行时错误。 • 使用Java的异常处理机制主要是处理运 行时的错误,异常就是运行时错误。
• 到目前为止,只是获取了被Java运行时系统 抛出的异常,并在catch块中进行处理。除了 捕获异常外,我们还可以在程序中主动抛出异 常和声明异常。 • 抛出异常 • 程序使用throw语句抛出异常。throw语句的 通常形式如下: • throw ThrowableInstance;
声明异常 • 有两种可以处理Throwable对象的方法:一种 是使用try…catch语句;另一种是使用throw s关键字声明异常。 • 如果一个方法可以导致一个异常但该方法并不 处理该异常,那么该方法使用throws子句来 声明该异常。含有throws子句的基本形式的 方法声明如下: ret-type methName(param-list) throws except-list{ //方法体 }

java异常处理练习题

java异常处理练习题

一、填空题1、计算机程序错误分为(语法错误)、(运行错误)和逻辑错误。

2、(Error)类及子类表示受检查异常,(Exception)类及子类表示不受检查异常。

3、自定义异常,需要利用extends继承(Exception)类。

二、选择题1、下面(C)语言提供了异常处理机制。

A、C语言B、C++语言C、Java语言D、Basic语言2、下面(C)不是异常情况。

A、数组下标越界B、死循环C、文件不能打开D、对象类型不匹配3、如果不希望方法来捕捉异常,采用(AB)关键字可以把该方法产生的异常抛出。

A、throwB、throwsC、gotoD、 break三、简答题1、什么是异常,它的作用有哪些。

异常是指应用程序在运行过程中发生的不正常现象,或发生的错误。

异常是程序运行中一些红正常的错误,它中断正在执行程序的正常指令流。

2、受检查异常与运行时异常的区别。

受检异常是严重的系统错误产生的异常对象,应用程序通常无法捕获,如系统资源耗尽、动态链接失败和线程死锁等原因造成的程序中断。

错误处理一般交由操作系统处理,程序本身不提供错误处理机制。

通常从采取退出运行,应用程序不需要也无法对错误对象进行监视和处理。

运行时异常是不受检异常,可以不编写异常处理的程序代码,依然可以成功编译,因为它是在程序运行时才有可能产生。

这类异常可能出现在程序的任何部分,而且数量很大,为了不淹没程序,通常应用程序不需要对不受检异常对象进行监视,可以通过java编译器的检查。

四、编程题1、定义一个方法,该方法能够捕捉文件打开异常、数组下标越界异常,抛出除数为0异常。

import java.io.IOException;import java.util.Scanner;public abstract class Text {public static void main(String[] args) throws IOException {int a;int m=100;System.out.println("input a number:");Scanner scanner;scanner=new Scanner(System.in);try{a=scanner.nextInt();System.out.println("a:"+a);double b=m/a;System.out.println("b=100/a="+b);}catch(Exception e){System.out.println("/by zero");}System.out.println("success");// TODO自动生成的方法存根}}import java.io.IOException;import java.util.Scanner;public abstract class Text {public static void main(String[] args) throws IOException { int[] a={5,0,4,10,25,20};int m=100;for (int i=0;i<a.length;i++)try{System.out.println("a:"+a[i]);double b=m/a[i];System.out.println("b=100/a="+b);}catch(ArrayIndexOutOfBoundsException e){System.out.println("out of");}catch(Exception e){System.out.println("/by zero");}System.out.println("success");// TODO自动生成的方法存根}}。

第6章 习题答案

第6章 习题答案

第6章习题
1. 关键字__throws__用来声明方法可能抛出的异常,关键字throw用来在方法中抛出异常。

2. 要捕获异常,使用的关键字__try__和__catch__。

3. 无论有无异常发生,始终要被执行的代码放在___finally___块中。

4. 简述Java程序中的三种错误?
答: 对于一个程序来说,可能会发生三种错误,语法错误、运行时错误和逻辑错误。

(1)语法错误的产生是在我们编写代码的过程中可能输入的字符错误,不符合相应的命令格式等;
(2)运行时错误是程序在运行中出现意料不到情况,如除数为零,数组越界等;
(3)逻辑错误是程序的运行结果和我们预想的结果不一致,这是一种难以调试的错误。

5. 简述使用try...catch处理异常的三种情况?
答:(1)第一种情况(try代码块不会产生异常) ,此时执行完try代码块,转而执行try…catch后的代码块;
(2)第二种情况(try代码块产生异常,并且与捕获的异常类型匹配),此时执行到产生异常代码时,转而执行相匹配的catch语句块,之后执行try…catch后的代码块;
(3)第三种情况(try代码块产生异常,并且与捕获的异常类型不匹配),当执行到产生异常的代码时,程序被中断。

ch06

ch06

第6章Java异常处理任何一个软件在运行中都会出现故障,在故障出现后需要有较为及时且有效的处理办法。

Java语言的异常处理机制是由捕获异常和处理异常两部分组成的。

本章主要介绍Java 语言的异常处理机制。

本章要点●异常和异常分类●Java异常处理机制●自定义异常本章难点●Java异常处理机制学习目标●理解Java异常处理机制。

●了解自定义异常。

6.1 异常处理概述6.1.1 异常及其分类任何计算机语言的程序都难免有漏洞,捕获错误最理想的是在编译期间,然而,在实际的程序设计中,并非所有错误都能在编译期间侦测到。

例如,下列情况在编译时通常检测不到:类文件丢失、想打开的文件不存在、网络连接中断、操作数超出预定范围等。

这些在程序执行中,中断正常程序流程的异常条件称为错误或异常。

Java中,所有的异常都由类来表示。

所有的异常类都是从一个名为Throwable的类派生出来的。

因此,当程序中发生一个异常时,就会生成一个异常类的某种类型的对象。

Throwable 有两个直接子类:Error和Exception。

Error类表示程序运行时发生的严重错误,Exception 类表示程序运行时产生的异常。

Error和Exception类又派生了很多子类用来表示程序运行产生的具体错误和异常。

例如使用NoClassDeFormatError表示没有类定义所产生的错误,使用ArithmeticException类表示算术运算产生的异常等。

Java中异常及其类的层次结构如图6-1所示:图6-1 异常类的层次结构异常类Exception的构造函数及常用方法:①Exception()建立一个没有详细信息的异常。

②Exception(String s)建立一个有详细信息的异常,当异常被捕获时,可以从信息当中得知错误发生的原因。

③获得异常的有关信息public String toString():返回描述异常类信息的字符串。

public void printStackTrace():在当前标准输出当前异常对象的堆栈使用轨迹。

JAVA期末复习题及答案——第六章

JAVA期末复习题及答案——第六章

JAVA期末复习题及答案——第六章一.填空题1.Java中的异常类对象是Error类或Exception类的对象,这两个类中 Error 类的对象不会被Java的应用程序捕获和抛出。

2.在下列程序的下划线处,填入适当语句使程序能正确执行并输出异常栈信息public class ThrowableException{public static void main(String args[]){try{throw new Throwable(“这是本人定义的异常”);}catch(Throwable e){System.out.println(“e.toString:”+e.toString());System.out.println(“e.printStackTrace():”);System.out.println(e.printStackTrace()) ;}}}二.选择题1.下列关于finally的说法正确的是:BA、如果程序在前面的catch语句中找到了匹配的异常类型,将不执行finally 语句块B、无论程序是否找到匹配的异常类型,都会去执行finally语句块中的内容C、如果在前面的catch语句块中找到了多个匹配的异常类型,将不执行finally 语句块D、只要有catch语句块,任何时候都不会执行finally语句块2.关于多个catch语句块的异常捕获顺序的说法正确的是:DA、父类异常和子类异常同时捕获B、先捕获父类异常C、先捕获子类异常D、依照catch语句块的顺序进行捕获,只能捕获其中的一个3.关于Java 异常,下列说法错误的是(D)A.异常是定义了程序中遇到的非致命的错误,而不是编译时的语法错误B.try……catch语句中对try 内语句监测,如果发生异常,则把异常信息放入对象e 中C.throws 用来表示一个方法有可能抛出异常给上一层,则在调用该方法时必须捕捉异常,否则无法编译通过D.主函数不可以使用 throws 抛出异常4.所有异常的父类是(B)。

练习10 Java异常处理练习题

练习10 Java异常处理练习题

Java异常处理练习题[] 选择题:1.问:如下哪些异常类的定义是合法的?A:class MyException implments Throwable {}B:public class MyException extends Exception {}C:public class MyException implements Exception {}D:public class MyException extends RuntimeException {} E:以上定义都不是答:2.问:下列哪些方法定义是合法的A:void a() throw Exception, IOException {}B:public void a() Throws IOException, Exception {}C:public void a() throws Exception, Error {}D:public void a() Throw String, Exception {}E:public void a() throws Object, Exception {}F:以上定义都合法。

答:3.给定代码:package com.ibm.oa.business;import java.io.*;public class Info{public void show() throws IOException, SQLException{---------------------------------------}}问:在划线部分,如下哪个语句是合法的?A:throws new Exception;B:throws new Exception(“Error”);C:throw new RemoteException(“Error”);E:throws IOException(“Error”);F:throw new BatchUpdateException();G:以上定义都不合法。

异常处理考试题及答案

异常处理考试题及答案

异常处理考试题及答案一、选择题(每题2分,共10分)1. 在Java中,以下哪个关键字用于声明异常?A. tryB. catchC. throwD. throws答案:D2. 当一个方法可能会抛出异常时,以下哪个选项是正确的处理方式?A. 忽略它B. 使用try-catch块捕获异常C. 使用finally块D. 以上都是答案:B3. 在Python中,以下哪个语句用于捕获异常?A. ifB. forC. whileD. try-except答案:D4. 在C++中,以下哪个关键字用于抛出异常?A. throwB. catchC. tryD. finally答案:A5. 在JavaScript中,以下哪个函数用于抛出异常?A. alert()B. console.log()C. throw()D. print()答案:C二、填空题(每题2分,共10分)1. 在Java中,如果一个方法声明了异常,那么调用该方法的代码必须使用__try-catch__块来捕获异常,或者在声明中使用__throws__关键字。

2. 在Python中,异常处理的基本结构是__try-except__块,其中__try__块包含可能引发异常的代码,__except__块包含异常发生时执行的代码。

3. 在C++中,异常处理使用__try__块来包围可能抛出异常的代码,使用__catch__块来捕获和处理异常。

4. 在JavaScript中,可以使用__try__块来包围可能抛出异常的代码,使用__catch__块来捕获异常。

5. 在异常处理中,__finally__块是一个可选的代码块,它在try-catch结构的末尾执行,无论是否发生异常。

三、简答题(每题10分,共20分)1. 描述Java中异常的两种类型,并给出一个例子。

答:Java中的异常分为检查型异常(checked exceptions)和非检查型异常(unchecked exceptions)。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

第6章异常处理机制
一、选择题
1.下列关于异常的说法正确的是(B)。

A.异常是编译时的错误
B.异常是运行时出现的错误
C.异常就是程序错误,程序错误就是异常
D.以上都不对
2.下列哪个类是异常类的父类(根类)(A)。

A.Exception
B.ArithmeticException
C.NullPointerException
D.ArrayIndexOutofBoundException
3.有关下列异常处理机制叙述正确的是(C)。

try{
可能产生异常的语句块;
}catch(exceptiontype1 e){
处理异常e的语句块;
}catch(exceptiontype2 e){
处理异常e的语句块;
}
……
finally{
最终处理语句块;
}
A.try子句可能有多个,catch子句可能有多个,finally子句必须有。

B.多个catch参数中的异常类可以有父子关系,但父类异常的catch子句应该在子类异常的catch子句前面。

C.如果try子句没有抛出任何异常,则跳过catch子句,转移到finally子句继续执行。

D.当try子句监视的语句块抛出异常时,运行时系统会根据catch子句的顺序,从第一个开始,逐个查找能够捕获该异常的catch子句并执行catch子句内的语句块以完成对异常的处理,然后继续执行后面的catch子句,最后转移到finally子句,执行该子句中的语句块。

4.有关throw和throws的说法中不正确的是(C)。

A.throw的作用是抛出异常,后面加的是异常类的对象。

B.throws的作用是向外抛出异常即声明要产生的若干异常,后面加的是异常类的类名。

C.throws只能声明要产生的自定义异常,也就是后面只能加自定义异常类。

D.以上都不对。

5.下列程序运行结果是(C)。

public class E {
public static void main(String argv[]){
E m = new E();
System.out.println(m.amethod());
}
public int amethod(){
int i, j=0;
try {
i=3/j;
j++;
} catch (ArithmeticException e) {
return j;
} catch (Exception e){
return 3;
}
return 2;
}
}
A.1 B.2 C.0 D.3
6.下列程序运行的结果是(A)。

public class E {
public static void main(String argv[]){
E m = new E();
System.out.println(m.amethod());
}
public int amethod(){
try {
int i, j=0;
i=3/j;
} catch (ArithmeticException e) {
System.out.println("0不能做除数");
return -1;
} catch(Exception e){
return -1;
} finally{
System.out.println("Doing finally");
}
return 0;
}
}
A.0不能做除数
Doing finally
-1
B.0不能做除数
-1
Doing finally
C.0不能做除数Doing finally
D.0不能做除数-1
二.编程题
1.编写一个异常类MyException,再编写一个类Student,该类有一个产生异常的方法:
public void speak(int m) throws MyException,要求参数m的值大于200时,方法输出信息“参数的值大于200。

”,否则抛出一个MyException对象。

最后编写主类,在主类的main 方法中用Student创建一个对象s,该对象调用speak方法。

1.class MyException extends Exception {
MyException(){
super("This is MyException class");
}
}
class Student {
public void speak(int m) throws MyException {
if (m>200) {
System.out.println("参数的值大于200。

");
} else {
throw new MyException();
}
}
}
class E {
public static void main(String[] args) {
Student s = new Student();
try {
s.speak(100);
}catch(MyException e) {
e.printStackTrace();
}
}
}。

相关文档
最新文档