实验六 Java 异常处理的程序设计; Java 自定 义异常的程序设计
一、实验目的
1、理解系统异常处理的机制。
2、创建自定义的异常类型。
二、实验学时
2 学时
三、实验类型 验证性实验
四、实验需求
1、硬件
每位学生配备计算机一台
2、软件
Windows 7 操作系统, JDK ,eclipse ,MySQL
3、网络
无
4、工具
无
五、实验理论与预备知识
1、异常的基本概念
2、异常处理语句的基本格式
3、自定义异常
六、实验内容与结果
1、编写应用程序, 从命令行输入表示两个小数参数的字符串, 求它们的商, 要求程序中捕 获 NumberFormatException 异常和 ArithmeticException 异常。
package book;
import java.util.Scanner;
public class Work6_1
{
public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
while(true)
{
try
{
System.out.println("input double a:");
double a=Double.parseDouble(input.nextLine());
System.out.println("input double b:");
double b=Double.parseDouble(input.nextLine());
if(b==0)
{
throw new ArithmeticException("除数=0,错误");
}
System.out.println("a/b="+a/b);
break;
}
catch (NumberFormatException e)
{
System.out.println(e.getMessage());
continue;
}
catch (ArithmeticException e)
{
System.out.println(e.getMessage());
continue;
}
}
}
}
参考代码:
2、编写一段程序,完善学生 student 类,增加输入学生的成绩的操作方法,如果小于 0 分或者 大于 100 分则抛出异常,并捕捉异常,输出提示信息:输入的学生成绩超出范围了!
参考代码(建议使用自定义异常实现):
package book;
class Student_6_2
{
private String name;
private int age;
private double score;
public void setname(String name)
{
this.name=name;
}
public void setage(int age)
{
this.age=age;
}
public void setscore(double score) throws Exception
{
if(score<0||score>100)
{
throw new Exception("输入的学生成绩超出范围了!");
}
this.score=score;
}
public String getname()
{
return this.name;
}
public int getage()
{
return this.age;
}
public double getscore()
{
return this.score;
}
public String toString()
{
return this.getname()+"\t"+this.getage()+"\t"+this.getscore();
}
}
public class Work6_2
{
public static void main(String[] args)
{
Student_6_2 st=new Student_6_2();
try
{
st.setage(21);
st.setname("yxc");
st.setscore(101.0);
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
System.out.println(st);
}
}