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+"岁,合理");
}
}