Java练习题16.2 异常处理

Java练习题16.2 异常处理

欢迎扫码关注微信公众号 “野心与家”

1、自定义一个除数为负数的异常类

package com.shangjiti.aoian;
public class No5 {
	public static void main(String[] args) throws Exception
	{ 
			try
			{
				divide(4,2);
			}
			catch(DivideByMiunsException e)
			{
				System.out.println(e.getMessage());
			}
			catch(ArithmeticException e)
			{
				System.out.println(e.getMessage());
			}
	}
	public static void divide(int x, int y) throws DivideByMiunsException,ArithmeticException
	{
		if(y<0)
			throw new DivideByMiunsException("除数为负数");
		else if(y==0)
			throw new DivideByMiunsException("除数为0");
		else 
			System.out.println(x/y);
	}
}
class DivideByMiunsException extends Exception
{
	public DivideByMiunsException()
	{
		
	}
	public DivideByMiunsException(String mess)
	{
		super(mess);
	}	
}

2、自定义一个异常类NoThisSoundException和一个Player类,在Player的play方法中使用自定义异常,要求如下:
(1)NoThisSoundException继承Exception类,类中有一个无参和一个接收一个String类型参数的构造方法,构造方法中都使用super关键字调用父类的方法。
(2)Player类中定义一个play(int inedex)方法,方法接收一个int类型的参数,表示播放歌曲的索引,当index>10时,play方法用throw关键自抛出NoThisSoundException异常,创建异常对象时,调入有参的构造方法,传入“您播放的歌曲不存在”。

(3)在测试类中创建Player对象,并调用play方法测试自定义的NoThisSoundException异常,使用try。。。catch语句捕获异常,调用NoThisSoundException的getMessage方法打印出异常信息

package com.shangjiti.aoian;
public class No2 {
	public static void main(String[] args) {
		try 
		{
			Player.play(9);
		}
		catch(Exception e)
		{
			System.out.println(e.getMessage());
		}
	}
}
class NoThisSoundException extends Exception
{
	public NoThisSoundException(String mess)
	{
		super(mess);
	}
}
class Player
{
	public static void play(int index)throws Exception
	{
		if(index>10)
			throw new NoThisSoundException("歌曲不存在...");
		System.out.println("歌曲真好听...");
	}
}

3、自定义异常类AgeException和People类,在People类中设置age属性的方法setAge中,对年龄的值进行检测,如果大于160或小于0,则抛出一个AgeException异常,创建异常对象时,调用有参的构造方法,传入年龄

package com.shangjiti.aoian;
public class No1 {
	public static void main(String[] args) {
		try 
		{
			People.setAge(180);
		}
		catch(Exception e)
		{
			System.out.println(e.getMessage());
		}
	}
}
class AgeException extends Exception
{
	public AgeException(String mess)
	{
		super(mess);
	}
}
class People
{
	public static void setAge(int age)throws Exception
	{
		if(age>160||age<0)
			throw new AgeException("年龄"+age+"岁,不合理");
		System.out.println("年龄"+age+"岁,合理");
	}
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值