码迷,mamicode.com
首页 > 编程语言 > 详细

Java中的异常处理1

时间:2020-11-12 14:18:54      阅读:10      评论:0      收藏:0      [点我收藏+]

标签: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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!