异常throw new Exception相关代码

<span style="font-size:18px;">package com.yunhe.xiawu;

//自己设置抛出异常信息
public class YiChangDemo {
	char sex;

	public void setSex(char sex) throws Exception {
		if ('男' == sex && '女' == sex) {
			this.sex = sex;
		} else {
			// 除了系统可以抛出异常,自己也可以设置抛出异常
			throw new Exception("你输入的不对,只能输入男和女");
		}
	}

	public static void main(String[] args) {
		try {
			// 假设用户输入性别时输入 b
			new YiChangDemo().setSex('b');
		} catch (Exception e) {
			System.out.println("输入错误");
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("程序结束");

	}

}
</span>
package com.yunhe.xiawu;

import java.util.Scanner;

public class YiChang {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		int res = 0, num1 = 0, num2 = 0;
		System.out.println("input num1");
		if (scanner.hasNextInt()) {
			num1 = scanner.nextInt();
		}
		System.out.println("input num2");
		if (scanner.hasNextInt()) {
			num2 = scanner.nextInt();
		}
		try {
			res = num1 / num2;
		} catch (Exception e) {
			System.out.println("除数不能为0");
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			System.out.println("不管程序报错不报错,finally里的程序都会执行");
		}
		System.out.println(res);

	}

}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值