(完整word版)实验四异常类的定义及处理

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

信息科学与工程学院《Java程序设计》上机实验报告
专业班级姓名学号
实验时间年月日指导教师成绩
主要实验记录及个人小结
(包括部分实验源程序、调试结果及实验结果分析等)
try
{
int test3[]=null;
test3[1]=100; //空指针无法赋值
}
catch (NullPointerException e)
{
System.out.println("捕获异常:\n"+e);
System.out.println(e.toString());
}
finally
{
System.out.println("捕获完成 \n\n");
}
}
}
(2).实验结果
步骤(6):将outofBound()方法中捕获异常的语句注释掉,重新编译程序实验结果:
编译通过,运行时出现错误
System.out.println(e.toString());
}
finally{
System.out.println("捕获完成\n\n");
}
}
static void nullPointer(){
try {
int test3[]=null;
test3[1]=100; //空指针无法赋值
}
catch (NullPointerException e){
System.out.println("捕获异常:\n"+e);
System.out.println(e.toString());
}
finally{
System.out.println("捕获完成 \n\n");
}
}
}
实验结果:
2.编写程序实现如下功能:计算两个数之和,参与求和运算的每个数的值都必须在10-20之间,当任意一个数超出范围时,抛出自己的异常。

(1)源程序
public class SelfException
{
public static void selfExceptionTest(int a,int b) throws NumberRangeException {
int answer;
if(( a>10& b <20)&( a>10& b<20))
{
answer=a+b;
System.out.println("两数之和为:"+answer);
}
else
throw new NumberRangeException("错误");
}
public void manager()
{
try
{
selfExceptionTest(55,100);
}
catch(NumberRangeException e)
{
System.out.println("输入数值超出范围,应该为10-20之间的整数");
}
}
public static void main(String args[])
{
SelfException s=new SelfException();
s.manager();
}
}
class NumberRangeException extends Exception
{
public NumberRangeException(String message)
{
super(message);
}
}
(2)实验结果
3.思考题
(1)翻译下列常用异常类的描述信息
OutOfMemoryError
A class instance creation expression, array creation expression , or string concatenation operatior expression throws an OutOfMemoryError if there is insufficient
e1.printStackTrace();
}
int i;
double[] a=new double[3];
StringTokenizer st=new StringTokenizer(s);
for(i=0;i<3&&st.hasMoreTokens();i++)
{
a[i]=Double.parseDouble(st.nextToken());
}
try{
Area n=new Area();
n.test(i,a);
}
catch(MyException e){
System.out.println("输入错误参数");
}
}
}
实验结果:
二.实验总结
通过本次实验,了解了java中的异常处理。

java通过面向对象的方法来进行异常处理。

在一个方法的运行过程中,如果发生了异常,则这个方法生产代表该异常的一个对象,并把它交给运行时系统,运行时系统寻找相应的代码来处理这一异常。

我们把生产的异常对象并把它交给运行时系统的过程成为抛出(Throw)异常。

运行时系统在方法的调用栈中查找从生产的异常发发开始回溯,直到找到包含相应异常处理的方法为止,这一过程称为捕获(Catch)一个异常。

Java程序在运行是如果引发了一个可识别的错误,就会产生一个与该错误相对应的异常类的对象,这个过程称为异常类的抛出。

根据异常类的不同,可分为系统自动抛出的异常和语句抛出的异常。

当一个异常被抛出时,应有专门的语句来接受这个被抛出的异常对象,这个过程被称为捕获异常,当一个异常类的对象被捕捉或接受后,用户程序就会发生流程的跳转,程序中止当前的流程二跳转至专门的异常语句处理模块,。

捕获异常是还可以使用finally语句,finally语句为异常处理提供一个出口。

注:“实验记录及个人小结”部分不够可另附页或在背面续写第页。

相关文档
最新文档