java小白——抛出异常再应用

任务一:
创建一个异常处理的类,程序中首先输出"这是一个异常处理的例子",然后在程序中主动产生一个“ArithmeticException”类型被“0”除的异常,并用“catch”语句捕获这个异常。最后通过“ArithmeticException”类的对象e的方法“getMessage”给出异常的具体类型并显示出来。finally中给出最后的输出语句。

package qaq;
import java.util.Scanner;
public class Test5 {
 static double Div(double x,double y){
	 if(y == 0)throw (new ArithmeticException("0不能做除数"));
	 return x/y;
 }
	public static void main(String[] args) {
	Scanner sc = new Scanner(System.in);
	double x = sc.nextDouble();
	double y = sc.nextDouble();
	try{
		double result = Div(x,y);
		System.out.println(result);
		
	}catch(ArithmeticException e){
		System.out.print(e.getMessage());
	}
	finally{
		System.out.println("Finally:must go inside finally");
	}
			

	}

}

在这里插入图片描述任务二:
用户输入数字代表天,如果数字值在1-7之间,提示今天是数字对应的星期几,如果输入数字不是1-7之间,则抛出异常;

package qaq;
import java.util.Scanner;
public class Test4 {
 static int Div(int x){
	 if(x <= 0 ||x >7) throw (new RuntimeException("请输入1-7以内的编号"));
	 return x;
 }
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		try{
			int x = Div(n);
		switch(x){
		case 1:
			System.out.print("周一");
		break;
		case 2:
			System.out.print("周二");
		break;
		case 3:
			System.out.print("周三");
		break;
		case 4:
			System.out.print("周四");
		break;
		
		case 5:
			System.out.print("周五");
		break;
		case 6:
			System.out.print("周六");
		break;
		case 7:
			System.out.print("周天");
		break;
		
		}
		}catch(RuntimeException e){
			System.out.print(e.getMessage());
		}
		

	}

}

在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值