zoukankan      html  css  js  c++  java
  • 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
    
    

    断点

  • 相关阅读:
    常用的gem source
    The `master` repo requires CocoaPods 0.29.0
    day 26 对象的封装 抽象和接口
    day25 面向对象继承 多态
    day24 面向对象 命名空间组合 以及继承
    day23 模块和包的复习 初识面向对象
    day22 模块和包
    day21 其他常用模块和异常处理
    day20 模块
    day19正则表达式和re模块
  • 原文地址:https://www.cnblogs.com/yang37/p/13818169.html
Copyright © 2011-2022 走看看