|
@@ -0,0 +1,64 @@
|
|
|
|
|
+package com.sf._01_异常入门.demo1;
|
|
|
|
|
+
|
|
|
|
|
+import java.util.Scanner;
|
|
|
|
|
+
|
|
|
|
|
+public class Test {
|
|
|
|
|
+
|
|
|
|
|
+ /**
|
|
|
|
|
+ * 需求: 要求大家设计一个工具类叫MathUtils
|
|
|
|
|
+ * 这里有一个方法divide(Integer a , Integer b) a/b;
|
|
|
|
|
+ *
|
|
|
|
|
+ * 在main 方法在控制台当中录入a 和b
|
|
|
|
|
+ * 调用divide 方法, 这个方法前后都有代码 , 验证a b 都为1 的情况 和 a =1 b =0 等0的情况
|
|
|
|
|
+ * 要提前处理异常
|
|
|
|
|
+ * @param args
|
|
|
|
|
+ */
|
|
|
|
|
+ public static void main(String[] args) {
|
|
|
|
|
+ /**
|
|
|
|
|
+ * try{
|
|
|
|
|
+ * 可以能会出现异常代码
|
|
|
|
|
+ * }catch(异常类型 e){
|
|
|
|
|
+ * 当出现了对应异常类型 解决方案
|
|
|
|
|
+ * }
|
|
|
|
|
+ */
|
|
|
|
|
+ Scanner scanner = new Scanner(System.in);
|
|
|
|
|
+ System.out.println("请录入第一个数字");
|
|
|
|
|
+ int num1 = scanner.nextInt();
|
|
|
|
|
+ System.out.println("请录入第二个数字");
|
|
|
|
|
+ int num2 = scanner.nextInt();
|
|
|
|
|
+
|
|
|
|
|
+ try {
|
|
|
|
|
+ System.out.println("前面正常代码");
|
|
|
|
|
+ System.out.println("前面正常代码");
|
|
|
|
|
+ System.out.println("前面正常代码");
|
|
|
|
|
+ MathUtils.divide(num1, num2);
|
|
|
|
|
+ // 创建一个Student stu= null stu.getAge();
|
|
|
|
|
+ Student student = null;
|
|
|
|
|
+ System.out.println(student.getName());
|
|
|
|
|
+ System.out.println("后续正常代码");
|
|
|
|
|
+ System.out.println("后续正常代码");
|
|
|
|
|
+ // 只能够去处理除数不为0 的异常 没有办法处理其他异常
|
|
|
|
|
+// }catch (ArithmeticException e){
|
|
|
|
|
+// System.out.println("除数不能为0 请重新输入");
|
|
|
|
|
+// }catch (NullPointerException e){
|
|
|
|
|
+// System.out.println("数据不能为空");
|
|
|
|
|
+// }
|
|
|
|
|
+ }catch (Exception e){
|
|
|
|
|
+ /**
|
|
|
|
|
+ * toString : 打印异常类型: 异常原因
|
|
|
|
|
+ */
|
|
|
|
|
+// System.out.println(e.toString())
|
|
|
|
|
+// ;
|
|
|
|
|
+ /**
|
|
|
|
|
+ * getMessage(); 打印异常原因
|
|
|
|
|
+ */
|
|
|
|
|
+// System.out.println(e.getMessage());
|
|
|
|
|
+ e.printStackTrace();
|
|
|
|
|
+ System.out.println("出现了异常");
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+ System.out.println("后续代码123");
|
|
|
|
|
+
|
|
|
|
|
+ }
|
|
|
|
|
+}
|