【JAVA课程作业】实验六 Java 异常处理的程序设计; Java 自定 义异常的程序设计

实验六 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);
	}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿斯卡码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值