Java中的異常處理1
阿新 • • 發佈:2020-10-15
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
now i is 0: Exception in thread "main" java.lang.ArithmeticException: / by zero
at cn.yang37.exception.Demo1.getRes(Demo1.java:19)
at cn.yang37.exception.Demo1.main(Demo1.java:13)
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+":\t"); 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