面向对象Java实验06异常处理.docx
《面向对象Java实验06异常处理.docx》由会员分享,可在线阅读,更多相关《面向对象Java实验06异常处理.docx(17页珍藏版)》请在冰豆网上搜索。
面向对象Java实验06异常处理
电子信息学院
实验报告书
课程名:
面向对象程序设计(Java)
题目:
实验06异常处理
实验类别:
【验证、设计】
班级:
BX1210
学号:
28
姓名:
俞佳星
一、实验目的
(1)了解异常处理方法。
(2)熟悉并掌握常见异常的捕获方法。
(3)熟悉JDK中已经定义的若干异常类的层次结构。
(4)掌握自定义异常类的创建方法。
(5)了解线程的概念。
(6)学习简单的多线程编程。
二、实验内容
(1)仔细读下面的JAVA语言源程序,当输入不同的n和i的值时,例如输入2和4,或者0和5,或者xyz和6,或者2和18等,分别给出程序的运行结果并分析之。
packagecn.edu.sdju.joshua.exception;
importjava.io.BufferedReader;
importjava.io.IOException;
importjava.io.InputStreamReader;
publicclassRuntimeExceptionDemo{
publicvoidgo()throwsIOException,NumberFormatException{
int[]ko=newint[15];
inta=123;
Stringxn,xi;
intn,i;
BufferedReaderbr=newBufferedReader(newInputStreamReader(System.in));
System.out.print("Enterthevalueofn&i:
");
try{
xn=br.readLine();
xi=br.readLine();
}catch(IOExceptione){
throwe;
}
try{
n=Integer.parseInt(xn);
i=Integer.parseInt(xi);
}catch(NumberFormatExceptione){
throwe;
}
try{
a=110/n;
ko[i]=100;
System.out.println("0--a="+a);
}catch(ArithmeticExceptione){
System.out.println("1--除数为0的错误,a值不变,a="+a);
}catch(ArrayIndexOutOfBoundsExceptionf){
System.out.println("2--数组索引值大于数组长度的错误!
");
}finally{
System.out.println("3--最后总会执行finally部分的代码!
");
}
System.out.println("4--前面未发生异常或异常处理完成(并未向主调方法继续抛出)"
+",转入go的正常流程!
");
}
publicstaticvoidmain(Stringargs[]){
try{
newRuntimeExceptionDemo().go();
}catch(IOExceptione){
System.out.println("5--go方法将IOException异常抛出,此处可捕获:
"
+e.getMessage());
System.exit(-1);
}catch(NumberFormatExceptione){
System.out.println("6--go方法将NumberFormatException异常抛出,此处可捕获:
"
+e.getMessage());
System.exit(-1);
}
System.out.println("7--go调用结束,继续main方法的正常流程!
");
}
}
附:
异常处理的结构如下。
try{
……
}
catch(异常类名异常形参名)
{……}
catch(异常类名异常形参名)
{……}
finally
{……}
说明:
①finally总是执行,它是异常处理的统一出口,常用来实现资源释放、文件关闭等功能。
②发生异常时,try块内的后续语句不再执行。
③catch按照次序进行匹配检查处理,找到一个匹配者,不再找其他;catch的排列要按照先个别化再一般化的次序(即:
如果待捕获的异常类型之间存在父子关系,应该将子类异常排在前,父类异常排在后)。
(2)运行下面的程序,给出程序的运行结果并分析之。
packagecn.edu.sdju.joshua.exception;
publicclassIndexOutOfBoundsDemo{
publicIndexOutOfBoundsDemo(){
try{
inta[]=newint[2];
a[4]=3;
System.out.println("Afterhandlingexceptionreturnhere?
");
}catch(IndexOutOfBoundsExceptione){
System.err.println("exceptionmsg:
"+e.getMessage());
System.err.println("exceptionstring:
"+e.toString());
e.printStackTrace();
}finally{
System.out.println("-------------------");
System.out.println("finally");
}
System.out.println("Noexception?
");
}
publicstaticvoidmain(Stringargs[]){
newIndexOutOfBoundsDemo();
System.out.println("Continuethemainmethod?
");
}
}
(3)编写程序实现如下功能:
生成并捕获到NegativeArraySizeException和IndexOutOfBoundsException类型的异常,并显示捕获到的异常信息。
然后在此基础上生成并捕获到NullPointerException类型的异常,并显示捕获到的异常信息。
(4)编写程序实现如下功能:
计算两个数之和,参与求和运算的每个数的值都必须在10-20之间,当任意一个数超出范围时,抛出自己的异常。
自定义异常的步骤:
①声明一个新的异常类,使之以Exception类或其他某个已经存在的系统异常类或用户定义异常类为父类。
②为新的异常类定义属性和方法,或重载父类的属性和方法,使这些属性和方法能够体现该类对应的错误信息。
(5)为GUI实验中的简单计算器添加输入非数值字符串时的异常处理代码,要求发生该异常时在GUI界面上给出文本或消息框提示。
给出运行结果和更改之后的关键代码。
三、实验结果(关键代码和运行结果)
(1)
图1-1
Main方法开始执行,调用RuntimeExceptionDemo()中的go()方法。
go()方new了一个称为br的BufferedReader。
然后读取两行从键盘输入的信息,并分别赋值给xn和xi。
在利用Integer的parseInt()方法将输入的xn和xi中的字符串转化成数字。
并赋值给n,i。
再将110除以n并赋值给a。
同时将a存入i所指定的数组空间中。
然后输出a的内容。
并执行finally中的代码。
Finally执行完后,执行finally之后的代码,最后返回Main方法。
并执行余下代码。
图1-2
开始的过程同上,但当执行到110除以n时,出错,进入异常处理,显示除数为0错误。
然后再执行finally中的代码,之后的执行过程与上面相同。
图1-3
开始的过程和图1-1的执行过程一样。
当执行到利用Integer的parseInt()方法将输入的xn和xi中的字符串转化成数字时,出错,并进入异常处理,抛出异常。
然后Main进行异常处理,向屏幕输出错误信息后,直接结束程序。
图1-4
开始的执行过程与之前一样。
当执行到再将110除以n并赋值给a。
同时将a存入i所指定的数组空间中时出错,进入异常处理。
显示数值越界信息。
然后,执行finally中的代码,之后执行finally之后代码。
然后返回main方法,执行余下的代码。
(2)
图-2运行结果
开始执行main方法,new一个IndexOutOfBoundsDemo类,执行IndexOutOfBoundsDemo的构造方法。
在构造方法中new了一个2个空间的数组。
然后再第四个空间中放入3。
这时出现异常,进入异常处理。
显示异常信息。
之后执行finally中的代码。
然后执行构造方法中余下的代码。
最后返回main方法,在执行余下的代码。
(3)
packagecn.edu.sdju.no28.johnson;
publicclassIndexOutOfBoundsDemo{
publicIndexOutOfBoundsDemo(){
try{
inta[]=newint[2];
a[4]=3;
System.out.println("Afterhandlingexceptionreturnhere?
");
}catch(ArrayIndexOutOfBoundsExceptione){
System.err.println("exceptionmsg:
"+e.getMessage());
System.err.println("exceptionstring:
"+e.toString());
e.printStackTrace();
}catch(IndexOutOfBoundsExceptione){
System.err.println("exceptionmsg:
"+e.getMessage());
System.err.println("exceptionstring:
"+e.toString());
e.printStackTrace();
}catch(NegativeArraySizeExceptione){
System.err.println("exceptionmsg:
"+e.getMessage());
System.err.println("exceptionstring:
"+e.toString());
e.printStackTrace();
}catch(NullPointerExceptione){
System.err.println("exceptionmsg:
"+e.getMessage());
System.err.println("exceptionstring:
"+e.toString());
e.printStackTrace();
}finally{
System.out.println("-------------------");
System.out.println("finally");
}
System.out.println("Noexception?
");
}
publicstaticvoidmain(Stringargs[]){
newIndexOutOfBoundsDemo();
System.out.println("Continuethemainmethod?
");
}
}
图3运行结果
(4)
packagecn.edu.sdju.no28.johnson;
publicclassmyexception{
publicstaticvoidmain(Stringargs[]){
exp();
}
staticvoidexp(){
try{
inta[]=newint[-1];
a[1]=1;
}catch(NegativeArraySizeExceptione){
System.out.println("error:
NegativeArraySizeException");
}
try{
intb[]=newint[2];
b[4]=3;
}catch(IndexOutOfBoundsExceptione){
System.out.println("error:
IndexOutOfBoundsException");
}
try{
Stringa[]=newString[2];
a=null;
System.out.println("length:
"+a.length);
}catch(NullPointerExceptione){
System.out.println("error:
NullPointerException");
}
}
}
图4运行结果
(5)
packagecn.edu.sdju.no28.johnson;
importjava.awt.*;
importjava.awt.event.*;
importjavax.swing.*;
@SuppressWarnings("serial")
classCalculatorUsingInnerClassextendsJFrameimplementsActionListener{
JPaneltopPal,cenPal,botPal;
JTextFieldtfOprand1;
JTextFieldtfOprand2;
JTextFieldtfRst;
JComboBoxlstOperator;
JLabellabAdd,labRst,labInfo;
JButtonbtnOperate,btnReset;
ContainerconPan=null;
publicCalculatorUsingInnerClass(){
topPal=newJPanel();
topPal.setLayout(newFlowLayout());
cenPal=newJPanel();
cenPal.setLayout(newFlowLayout());
botPal=newJPanel();
botPal.setLayout(newFlowLayout());
tfOprand1=newJTextField(8);
tfOprand2=newJTextField(8);
tfRst=newJTextField(8);
StringlstItem[]={"+","-","*","/"};
lstOperator=newJComboBox(lstItem);
labRst=newJLabel("=");
btnOperate=newJButton("开始计算");
btnOperate.setFont(newFont("楷体",Font.BOLD,16));
btnReset=newJButton("清除");
labInfo=newJLabel("");
labInfo.setForeground(Color.RED);
labInfo.setFont(newFont("黑体",Font.PLAIN,16));
conPan=this.getContentPane();
conPan.setLayout(newBorderLayout());
conPan.add(cenPal,BorderLayout.CENTER);
conPan.add(topPal,BorderLayout.NORTH);
conPan.add(botPal,BorderLayout.SOUTH);
cenPal.add(tfOprand1);
cenPal.add(lstOperator);
cenPal.add(tfOprand2);
cenPal.add(labRst);
cenPal.add(tfRst);
topPal.add(btnOperate);
topPal.add(btnReset);
botPal.add(labInfo);
//设置窗口居中显示
this.setLocationRelativeTo(null);
this.setVisible(true);
btnOperate.addActionListener(this);
btnReset.addActionListener(this);
this.addWindowListener(newWindowListener(){
publicvoidwindowClosing(WindowEvente){
System.exit(0);
}
@Override
publicvoidwindowActivated(WindowEventarg0){
//TODO自动生成的方法存根
}
@Override
publicvoidwindowClosed(WindowEventarg0){
//TODO自动生成的方法存根
}
@Override
publicvoidwindowDeactivated(WindowEventarg0){
//TODO自动生成的方法存根
}
@Override
publicvoidwindowDeiconified(WindowEventarg0){
//TODO自动生成的方法存根
}
@Override
publicvoidwindowIconified(WindowEventarg0){
//TODO自动生成的方法存根
}
@Override
publicvoidwindowOpened(WindowEventarg0){
//TODO自动生成的方法存根
}
});
}
publicstaticvoidmain(Stringargs[]){
CalculatorUsingInnerClassmainFrame=newCalculatorUsingInnerClass();
mainFrame.setSize(400,150);
mainFrame.setTitle("GUI实验——简单算术运算器");
}
publicvoidactionPerformed(ActionEventarg0){
if(arg0.getActionCommand().compareTo("开始计算")==0){
if("".equals(tfOprand1.getText().trim())||
"".equals(tfOprand1.getText().trim()))
labInfo.setText("加数和被加数均不允许为空!
");
else{
doublea;
doubleb;
try{
a=Double.valueOf(tfOprand1.getText()).doubleValue();
b=Double.valueOf(tfOprand2.getText()).doubleValue();
}catch(NumberFormatExceptione){
labInfo.setText("对不起只能计算数字!
");
return;
}
charoperator=((String)lstOperator.getSelectedItem()).charAt(0);
doubleresult=0;
switch(operator){
case'+':
result=a+b;break;
case'-':
result=a-b;break;
case'*':
result=a*b;break;
case'/':
result=a/b;break;
}
tfRst.setText(String.valueOf(result));
}
}else{
tfOprand1.setText("");
tfOprand2.setText("");
tfRst.setText(String.valueOf(""));
labInfo.setText("以上文本框中的内容已清除!
");
}
}
}
图5运行结果
四、实验体会
在本次实验中我了解异常处理方法。
对以前没有的接触过的异常处理有了基本的了解。
同时我们熟悉并掌握常见异常的捕获方法。
利用try,catch()方法捕获异常,并在此进行异常处理。
除此之外还有finally等关键字的特殊用法。
我们也熟悉了JDK中已经定义的若干异常类的层次结构。
同时我们也掌握自定义异常类的创建方法。
当然,实验的过程也不是一帆风顺的。
实验的过程中出现了很多的问题。
比如在第四个小实验中,我一直无法引起NullPointerException这个异常。
在查阅了API文档之后发现只有在当应用程序试图在需要对象的地方使用 null 时,抛出该异常。
这种情况包括:
调用 null 对象的实例方法