异常处理示例: 除法 ( 输入数据是否合法/除数是否不为0 )

package com.one.test;

import java.util.InputMismatchException;
import java.util.Scanner;
/**
 * 异常处理
 * @author Administrator
 */
public class Test2 {

	public static void main(String[] args) {
		
		//扫描器
		Scanner input = new Scanner(System.in);
		
		int a = 0;
		int b = 0;
		
		//计算
		int result = 0;
		
		while (true) {
			try {
				//被除数
				System.out.print("请输入被除数:");
				a = input.nextInt();
				//除数
				System.out.print("请输入除数:");
				b = input.nextInt();

				result = a / b;

				System.out.println(a + " ÷ " + b + " = " + result);
				
				break;

			} catch(InputMismatchException e) {
				System.out.println("您输入的数据不合法, 请输入整数!");
				//清理扫描器内容, 方法1
				input.nextLine();
				//清理扫描器内容, 方法2
//				String garbage = input.next();
				
			} catch (ArithmeticException e) {
				System.out.println("除数不能为0, 请重新输入!");
				
				//获取异常信息
				System.out.println(e.getMessage());
				//打印异常链信息
				e.printStackTrace();
				
			} catch (Exception e) {
				System.out.println("您输入的数据有误, 请重试!");
			} 
		}		
	}	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值