Java中的异常处理1

2021-03-18 15:25

阅读:369

标签:catch   cat   sys   exce   ESS   ini   运行   package   tac   

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

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

技术图片

  • 做了异常处理
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

技术图片

Java中的异常处理1

标签:catch   cat   sys   exce   ESS   ini   运行   package   tac   

原文地址:https://www.cnblogs.com/yang37/p/13818169.html


评论


亲,登录后才可以留言!