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("您输入的数据有误, 请重试!");
}
}
}
}
异常处理示例: 除法 ( 输入数据是否合法/除数是否不为0 )
最新推荐文章于 2022-10-16 22:07:10 发布