java考试题库第六章.docx
- 格式:docx
- 大小:61.90 KB
- 文档页数:10
第六章异常和异常处理一、选择题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语言程序设计第六章课后习题答案1.将本章例6-1至6-18中出现的文件的构造方法均改为使用File类对象作为参数实现。
个人理解:File类只能对整文件性质进行处理,而没法通过自己直接使用file.Read()或者是file.write()类似方法对文件内容进行写或者读取。
注意:是直接;下面只提供一个例2变化,其他的你自己做,10几道啊,出这题的人真他妈有病。
import java.io.*;public class test6_2{public static void main(String[] args) throws IOException { String fileName = "D:\\Hello.txt";File writer=new File(fileName);writer.createNewFile();BufferedWriter input = new BufferedWriter(newFileWriter(writer));input.write("Hello !\n");input.write("this is my first text file,\n");input.write("你还好吗?\n");input.close();}}运行结果:(电脑系统问题,没法换行,所以一般使用BuffereWriter中newLine()实现换行)2.模仿文本文件复制的例题,编写对二进制文件进行复制的程序.// CopyMaker类import java.io.*;class CopyMaker {String sourceName, destName;BufferedInputStream source;BufferedOutputStream dest;int line;//打开源文件和目标文件,无异常返回trueprivate boolean openFiles() {try {source = new BufferedInputStream(newFileInputStream( sourceName ));}catch ( IOException iox ) {System.out.println("Problem opening " + sourceName );return false;}try {dest = new BufferedOutputStream(newFileOutputStream( destName ));}catch ( IOException iox ){System.out.println("Problem opening " + destName );return false;}return true;}//复制文件private boolean copyFiles() {try {line = source.read();while ( line != -1 ) {dest.write(line);line = source.read();}}catch ( IOException iox ) {System.out.println("Problem reading or writing" );return false;}return true;}//关闭源文件和目标文件private boolean closeFiles() {boolean retVal=true;try { source.close(); }catch ( IOException iox ) {System.out.println("Problem closing " + sourceName );retVal = false;}try { dest.close(); }catch ( IOException iox ) {System.out.println("Problem closing " + destName );retVal = false;}return retVal;}//执行复制public boolean copy(String src, String dst ) {sourceName = src ;destName = dst ;return openFiles() && copyFiles() && closeFiles();}}//test6_2public class test6_2{public static void main ( String[] args ) {String s1="lin.txt",s2="newlin.txt";if(new CopyMaker().copy(s1, s2))S ystem.out.print("复制成功");elseS ystem.out.print("复制失败");}}运行前的两个文本:lin.txt和newlin.txt(为空)运行后:3.创建一存储若干随机整数的文本文件,文件名、整数的个数及范围均由键盘输入。
《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++)<>。
第六章6.1 设计一个面板,该面板中有四个运动项目选择框和一个文本区。
当某个选择项目被选中时,在文本区中显示该选择项目。
程序运行结果:源文件:Work6_1.javaimport javax.swing.*;import java.awt.*;import ;/*** 6.1设计一个面板,该面板中有四个运动项目选择框和一个文本区。
<BR>*当某个选择项目被选中时,在文本区中显示该选择项目。
<BR>*@author黎明你好*/public class Work6_1 extends JFrame{private static final long serialVersionUID = 1L;private MyPanel6_1 panel;// 此面板public Work6_1(){super("第六章,第一题");panel = new MyPanel6_1();this.add(panel);this.setBounds(100, 100, 400, 150);this.setVisible(true);this.validate();this.addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}});}public static void main(String args[]){new Work6_1();}}面板类源文件:MyPanel6_1.java/***需要设计的面板类*/class MyPanel6_1 extends JPanel implements ItemListener{private static final long serialVersionUID = 1L;private JCheckBox box1, box2, box3, box4;private JTextArea textArea;public MyPanel6_1(){textArea = new JTextArea(5, 10);box1 = new JCheckBox("足球");box2 = new JCheckBox("排球");box3 = new JCheckBox("篮球");box4 = new JCheckBox("台球");box1.addItemListener(this);box2.addItemListener(this);box3.addItemListener(this);box4.addItemListener(this);this.add(box1);this.add(box2);this.add(box3);this.add(box4);this.add(textArea);this.setBackground(Color.cyan);}public void itemStateChanged(ItemEvent e){JCheckBox box = (JCheckBox) e.getSource();if (box == box1 && box.isSelected())textArea.append(box1.getText() + "\n");else if (box == box2 && box.isSelected())textArea.append(box2.getText() + "\n");else if (box == box3 && box.isSelected())textArea.append(box3.getText() + "\n");else if (box == box4 && box.isSelected())textArea.append(box4.getText() + "\n");}}6.2 设计一个面板,该面板中有四个运动项目单选框和一个文本框。
第6章共享与数据保护一、单选题1.已知print()函数是一个类的常成员函数,无返回值,下列正确的原型声明(A)。
A.void print()const;B.const void print();C.void const print();D.void print(const);2.有以下类的说明,请指出错误的地方(A)。
class CSample{const int a=2.5;//Apublic:CSample();//BCSample(int val);//C~CSample();//D};3.下列关于静态成员的描述中,错误的是(C)。
A.静态成员都使用static来说明B.静态成员属于某一个类,而不专属于某一对象C.静态成员只能用类名加作用域运算符引用,不可以通过对象来引用D.静态数据成员的初始化是在类体外进行的4.下列关于常成员的描述中,错误的是(C)。
A.常成员是用关键字const来说明的B.常成员有常数据成员和常成员函数两种C.常数据成员的初始化可以在定义类的类体内用形如const int a=10;的方式进行D.常数据成员的值是不可以改变的5.有以下类的说明,下列哪一种构造函数无法对常数据成员a正确初始化(C)。
class CSample{const int a;public://构造函数代码,见下面的选项};A.CSample():a(24){}B.CSample(int m):a(m){}C.CSample(){a=24;}D.CSample(int m):a(m+24){}6.设类AA内定义了一个int型的静态数据成员a,下列哪种方式对a的初始化正确(D)。
A.在类AA的定义体内用static int a=20;B.在类AA的定义体外单独用语句static int a=20 ;C.在类AA的定义体外单独用语句static int AA∷a=20;D.在类AA的定义体外单独用语句int AA∷a=20;7.关于静态成员函数,下列说法不正确的是(A)。
第六章常用类6-1编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串。
但要保证汉字不被截半个,如"我ABC" 4 ,应该截为"我AB",输入〃我ABC 汉DEF" 6 ,应该输出"我ABC"而不是"我ABC+汉的半个"。
答案:packagetest;classSplitStri ng{StringSplitStr;intSplitByte;publicSplitString(Stringstr,i ntbytes){SplitStr=str;SplitByte=bytes;System.out.printlnC^heStringis: ,,'+SplitStr+'M;SplitBytes=',+SplitByte);}publicvoidSplitlt(){in tloopCo unt;loopCount=(SplitStr.length()%SplitByte==0)?(SplitStr,length()/SplitByte):(SplitStr.length()/SplitByte+1);System.out.println("W il lSplitinto”+loopCount);for(inti=1 ;iv=loopCount;i++)if(i==loopCount){ System.out.println(SplitStr.substring((i-1)*SplitByte,SplitStr.length())); }else{System.out.println(SplitStr.substring((i-1)*SplitByte,(i*SplitByte)));}}publicstaticvoidmai n(Strin g[]args){SplitStringss=newSplitString(H test 中dd 文dsaf 中男大3443n 中国43 中国人0ewldfls=103n,4);ss.Splitlt();}}6-2使用String类的public String concat(String str)方法可以把调用该方法的字符串与参数指定的字符串连接,把str指定的串连接到当前串的尾部获得一个新的串。
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;}}。
第六章异常处理 (2)一、选择题 (2)二、填空题 (6)三、判断题 (8)第七章输入/输出 (8)一、选择题 (8)二、填空题 (15)三、判断题 (18)四、读程序题 (20)五、编程题 (26)第八章基于Swing 的图形化用户界面 (28)一、选择题 (28)二、填空题 (37)三、判断题 (39)四、程序填空 (40)第十章多线程 (55)一、填空题 (55)三、判断题 (66)第十二章JDBC技术 (67)一、选择题 (67)二、填空题 (68)三、判断题 (69)四、程序填空 (69)第六章异常处理一、选择题1、无论是否发生异常,都需要执行()A、try语句块B、catch语句块C、finally语句块D、return语句答案:c2、异常处理变量()。
A、应用public关键字B、可以应用protected关键字C、可以应用private关键字D、只能在异常处理方法内使用。
答案:d3、通常的异常类是()A、ExceptionB、exceptionC、CommonExceptionD、ExceptionShare 答案:a4、异常产生的原因很多,常见的有()。
A、程序设计本身的错误B、程序运行环境改变C、软、硬件设置错误D、以上都是答案:a5、下列什么是除0异常()。
A、RuntimeExceptionB、ClassCastExceptionC、ArihmetticExceptionD、ArrayIndexOutOfBoundException答案:c6、读下面代码,哪个选项是正确的()import java.io.*;public class Test2{public static void main(String []args)throws IOException{i f(args[0]==”hello”)throw new IOException();}}A、没有错误,程序编译正确B、编译错误,不能够在main方法中抛出异常C、编译错误,IOException是一个系统异常,不能够由application程序产生D、没有输出结果答案:a7、当变异并且运行下面程序时会出现什么结果?()public class ThrowsDemo{static void throwMethod() {System.out.print("Inside throwMethod");throw new IOException("demo");}public static void main(String [] args){try{throwMethod();}catch(IOException e){System.out.println("Cauht"+e);}}}A、编译错误B、运行错误C、编译成功,但不会打印出任何结果D、没有输出结果答案:A8、执行下面程序的结果是什么?其中a=4,b=0 ()public static void divide(int a,int b){try{ int c = a / b; }catch(Exception e){System.out.println("Exception");}finally{System.out.println("Finally");}}A、打印Exception finallyB、打印FinallyC、打印ExceptionD、没有输出结果答案:A9、假定一个方法会产生非RuntimeException异常,如果希望把异常交给调用该方法的方法处理,正确的声明方式是什么?()A、throw ExceptionB、throws ExceptionC、new ExceptionD、不需要指明什么答案:B10、阅读下面的代码段、try{tryThis();return;}catch(IOException x1){System.out.println(“exception 1”);Return;}catch(Exception x2){System.out.println(“exception 1”);Return;}finally{System.out.println(“finally”)}如果tryThis()抛出一个IOException,那么屏幕的输出是什么?()A、”exception 1”后面跟着”finally”B、” exception 2”后面跟着“finally”C、”exception 1”D、”exception 2””答案:A11、下列哪些内容不是异常的含义?()A、程序的语法错B、程序编译或运行中所发生的异常事件C、程序预先定义好的异常事件D、程序编译错误答案:A12、自定义的异常类可从下列哪个类继承?()A、Error类B、AWTErrorC、VirtualMachineErrorD、Exception及其子集答案:D13、当方法遇到异常又不知如何处理时,下列哪种做法是正确的?()A、捕获异常B、抛出异常C、声明异常D、嵌套异常答案:B14、如要抛出异常,应用下列哪种子句?()A、catchB、throwC、tryD、finally答案:B15、下列选项中属于Exception异常的是()A、ArithmeticExceptionB、nullPointerExceptionC、classcastExceptionD、以上都是答案:A16、以下是异常的处理,哪个选项是正确的()A、book()throws exceptionB、book(int a)exceptionC、book()throwsD、book()throw exception答案:A17、将需要处理异常作为()语句块的一个参数来进行声明A、tryB、catchC、finallyD、以上都不对答案:B18、try语句块可以()A、拥有惟一的一个catch语句块B、多个finally语句块C、一个或多个catch语句块D、以上答案都不对答案:C19、下列什么是所有Exception和Error类的共同超类()A、ThrowableB、CheckedExceptionC、CatchableD、RuntimeException答案:A20、假定一个方法可能会产生非RuntimeException异常,如果希望把异常交给调用该方法的方法处理,正确的声明方式是()A、throws ExceptionB、throw ExceptionC、new ExceptionD、不需要指明什么答案:A21、try代码块中包含的是可能引起一个或多个异常代码,能够抛出异常的代码必须位于()代码块中。
第六章异常和异常处理一选择题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的子类。
(对)6-5.Throwable类有两个子类:Enor类和Exception类。
前者由系统保留,后者供应用程序使用。
(对)6・6.异常通常是指Error类和Exception类。
(错)6-7.Exception 类只有一个子类为RuntimeException o(错)68在异常处理屮,出现异常和抛出异常是一回事。
(错)6・9.运行时异常是在运行时系统检测并处理的。
(错)6-10.使用try-catch-finally语句只能捕获一个异常。
(错)6・11 •捕获异常时try语句后面通常跟有一个或多个catch ()方法用来处理try块内牛成的异常事件。
(对)6・12・使用finally语句的程序代码为该程序提供一个统一的的出口。
(对)6・13.抛出异常的方法说明中要加关键字throws,并在该方法屮还应添加throw语句。
(对)6・14.创建异常类时要给出该异常类的父类。
(对)6J5.如果异常类没有被捕获将会产生不正常的终止。
(对)三分析程序的输出结果6・1. Exer6_l.javapublic class Exer6_lpublic static void main(String args[])int x=10,y=0;int z=x/y;System.out.println(u z="+z);}}该程序运行后,输岀结果如图所示:D:\JAVA\XT>java Exer6_lException in thread"main^ng.ArithmeticException:/by zero At Exer6_l .main<Exer6_l .java:6>6・ 2.Exer6_2.javapublic class Exer6_2{public static void main(String args[]){int array 1[]={ 6,0,8};for(int i=0;i<array 1 .length;i++){try{int d=100/array[i];System.out.println( ^\t 正常:d= "+d);} catch(ArithmeticException e){System.out.println("\t 算术异常”);} catch(ArrayIndexOutOfBoundsException e){System.out.println("\t 下标越界异常”);}finally{System.out.println("\t 异常处理结束! \n H);运行该程序后,输出如图所示D:\JAVA\XT>java Exer6_2 正常:d二16 界常处理结束!算术异常!异常处理结束!正常:d=12异常处理结束!下标越界异常!异常处理结束!6-3 Exer6_3.javapublic class Exer6_3{public static void main(String args[]){ 〜int array 1[]={ 6,0,8}; for(int i=0;i<=array 1 .length;i++) {try{int d=100/arrayl[i]; System.out.println("\t 正常:d二"+d);1 catch(RuntimeException e) { ”System.out.println("\t 异常':"+e.toString());} finally{System.out.println(H\t 异常处理结束! \n n); }}运行该程序后,输岀结果如图所示:D:\JAVA\XT>java Exer6_3 正常:d=16 界常处理结朿!异常:ng.ArilhmeticException:/by zero 异常处理结束!正常:d=12异常处理结束!异常:ng.ArrayIndexOutOfBoundsExcepiton:3 异常处理结束!6-4 Exer6_4.javapublic class Exer6_4{public static void Test(){int a[]=new int[3];for(int i=O;i<=a.length;i++){try{a[i]=i+5;System.out.println("\t 正常:a["+i+n]=,'+a[i]); }catch(ArrayIndexOutOfBoundsException e){System.out.println(H\t 异常:+e.toString()H); throw e;public static void main(String args[]){try{Test();}finally{System.out.println("\t 异常处理结束! \n H)}}运行该程序后,输岀结果如图:D:\JAVA\XT>java Exer6_4正常:alO]=5正常:a[l]=6正常:a[2]=7异常:javaJang.AmiylndexOulOfBoudsExceplion: 3 异常处理结束!Exception in thread "main9 ng.AiTayIndexOutOfBoundsExcepiton:3 at Exer6_4.Test<Exer6_4.java: 1()> at Exer6_4.main<Exer6_4java:24>6-5 Exer6_5.javaclass myException extends Exception{static int a=0myException(String s){super(s); a++;}String show(){return11自定义异常出现的次数:”+a;}}Public class Exer6_5{static void Test() throws myException{myException e;e=new myException(H自定义异常\n”); throw e;}Public static void main(String argsfl){for(int i=0;iv3;i++){try{Test();1catch(myException e){System.out.println(e.show());System.out.println(e.toString);运行该程序后,输岀结果如图所示:D:\JAVA\XT>java Exer6_5 自定义异常出现的次数:1 myException:自定义异常自定义异常出现的次数:2 myException: 口定义异常自定义异常出现的次数:3 my Exception:自定义界常5.简单回答题6-1检测异常事件必须使用什么语句?答:try语句6-2 catch()方法的作用是什么?该方法用户能否调用?答:用来处理try块中检测出的异常事件。
6-3 catch()方法中异常类型应与什么相符?答:与生成的异常事件类型相符。
6-4异常示被捕获到将会出现什么现象?答:try语句后边的惯常处理代码将不被执行,通常使用finally语句提供一个统一出口。
6-5在一个try语句的程序代码块中可以捕获多个异常吗?答:可以6-6使用throw语句抛出的是类型还是对象?答:抛出的是对象。
6-7捕获到的异常还可以再抛出吗?答:可以。
6-8 Finally语句块中的代码何时被执行?答:在异常事件处理的方法catch()执行后执行。
6-9语句throw的作用是什么?答:抛出所检测到的异常。
6-10 异常类Exception的父类是什么?答:是Throwable 类。
6.编程题6-1编程实现下述异常,并输出显示适当的错误信息。
(1)数组卜标越界异常ArraylndexOutOfBoundsException类型。
例如,char ch[]=new char[5];ch[5]=W;〃产生该类型异常(2)对象转换异常ClassCastException类型。
例如,将对象al转换为对象a2时,如果al和a2不是同类,并且al也不是a2 的子类对彖时,则产生该类型异常。
(3)引用空对象的变量和方法时产生NullPointerException异常类型。
例如,int arf]=null;System.out.println (ar.length);〃产生该类异常(1)关于数组下标越界异常ArraylndexOutOfBoundsException请参照本书本章例6.1的程序,请读者自行编写。