代码改变世界

java try-catch-finally输出异常

2017-06-26 16:12  backyyan  阅读(1132)  评论(0编辑  收藏  举报
import java.util.Scanner;
import java.util.InputMismatchException;

public class TestException {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int a, b;
        try {
            System.out.print("请输入被除数");
            a = input.nextInt();
            System.out.print("请输入除数");
            b = input.nextInt();
            System.out.println("两数相除的结果为:" + a / b);
        } catch (InputMismatchException e) {
            System.out.println("你输入的不是数字,在这里必须输入数字");
        } catch (ArithmeticException e) {
            System.out.println("输入错误,除数不能为零");
            System.out.println(e.getMessage());

        } catch (Exception e) {
            System.out.println("程序出错了");
        } finally {
            System.out.println("无论是否出现异常,这里都会执行");

        }
    }
}