Java中的异常处理1_为何使用异常

1.编译时异常

2.运行时异常

  • 不处理异常
package cn.yang37.exception;

/**
 * @Class: Demo1
 * @Author: Yiang37
 * @Date: 2020/10/14 23:37
 * @Description:
 */
public class Demo1 {
    public static void main(String[] args) {
        for (int i = 5; i >=-3 ; i--) {
            System.out.println("now i is "+i+": "+getRes(5,i));
        }
    }

    static String getRes(int a, int b){
        return ""+(a/b);
    }
}
now i is 5: 1
now i is 4: 1
now i is 3: 1
now i is 2: 2
now i is 1: 5
Exception in thread "main" java.lang.ArithmeticException: / by zero
	at cn.yang37.exception.Demo1.getRes(Demo1.java:17)
	at cn.yang37.exception.Demo1.main(Demo1.java:12)

Process finished with exit code 1

打断点,程序异常后退出.

断点0

  • 做了异常处理
package cn.yang37.exception;

/**
 * @Class: Demo1
 * @Author: Yiang37
 * @Date: 2020/10/14 23:37
 * @Description:
 */
public class Demo1 {
    public static void main(String[] args) {
        for (int i = 5; i >=-3 ; i--) {
            System.out.print("now i is "+i+": ");
            try {
                System.out.println(getRes(5, i));
            }catch (Exception e){
                System.out.println("本次出现异常");
                e.printStackTrace();
            }
        }
    }

    static String getRes(int a, int b){
        return ""+(a/b);
    }
}
now i is 5: 1
now i is 4: 1
now i is 3: 1
now i is 2: 2
now i is 1: 5
now i is 0: 本次出现异常
java.lang.ArithmeticException: / by zero
	at cn.yang37.exception.Demo1.getRes(Demo1.java:23)
	at cn.yang37.exception.Demo1.main(Demo1.java:14)
now i is -1: -5
now i is -2: -2
now i is -3: -1

断点

posted @ 2020-10-14 23:56  羊37  阅读(95)  评论(0编辑  收藏  举报