1 package day4.haifei03;
2
3 import java.text.ParseException;
4 import java.text.SimpleDateFormat;
5 import java.util.Date;
6
7 /*
8 3.6 throws方式处理异常
9 并不是中所有的情况我们都有权限利用try-catch进行异常处理,针对我们处理不了的情况,Java提供了throws处理
10 throws格式是跟在方法的括号后面的
11 编译时异常必须要进行处理,两种处理方案:try-catch 或者 throws
12 如果采用 throws 这种方案,将来谁调用谁处理
13 运行时异常可以不处理,出现问题后,需要我们回来修改代码
14 */
15 public class ExceptionDemo4 {
16
17 /*public static void main(String[] args) {
18 System.out.println("begin");
19 method();
20 System.out.println("end"); //仅throws未try-catch时并不执行
21 }*/
22
23 //运行时异常
24 public static void method() throws ArrayIndexOutOfBoundsException{
25 int[] arr = {1, 2, 3};
26 System.out.println(arr[4]);
27 }
28
29 public static void main(String[] args) {
30 System.out.println("begin");
31 // show(); //编译时异常,谁调用谁处理
32 try {
33 show(); //ok,不再红色波浪线提醒
34 }catch (ParseException e){
35 e.printStackTrace();
36 }
37 System.out.println("end");
38 }
39
40 //编译时异常
41 public static void show() throws ParseException {
42 String s = "2021-05-19";
43 SimpleDateFormat sdf = new SimpleDateFormat();
44 Date d = sdf.parse(s);
45 System.out.println(d);
46 }
47
48 }