
1 package day4.haifei03;
2
3 /*
4 3 异常
5
6 3.1异常就是程序出现了不正常的情况
7 异常体系-图
8
9 3.2JVM默认处理异常的方式
10 如果程序出现了问题,我们没有做任何处理,最终JVM 会做默认的处理,处理方式有如下两个步骤:
11 把异常的名称,错误原因及异常出现的位置等信息输出在了控制台
12 程序停止执行
13
14 3.3try-catch方式处理异常
15 格式
16 try {
17 可能出现异常的代码;
18 } catch(异常类名 变量名) {
19 异常的处理代码;
20 }
21 流程
22 程序从 try 里面的代码开始执行
23 出现异常,就会跳转到对应的 catch 里面去执行
24 出现异常时会自动生成一个异常类对象,该对象被提交给Java运行时系统
25 Java运行时系统收到该对象时,会到catch中找到匹配的异常类然后处理
26 执行完毕之后,程序还可以继续往下执行
27
28 */
29 public class ExceptionDemo1 {
30
31 public static void main(String[] args) {
32 System.out.println("begin");
33 method();
34 System.out.println("end"); //未try-catch时不执行,try-catch时执行
35 }
36
37 /*public static void method(){
38 int[] arr = {1, 2, 3};
39 System.out.println(arr[1]); //ok
40 System.out.println(arr[3]); //ArrayIndexOutOfBoundsException
41 }*/
42
43 public static void method(){
44 try {
45 int[] arr = {1, 2, 3};
46 System.out.println(arr[1]);
47 System.out.println(arr[3]); //new ArrayIndexOutOfBoundsException();
48 }catch (ArrayIndexOutOfBoundsException e){
49 // System.out.println("你访问的数组索引不存在");
50 e.printStackTrace();
51 }
52 }
53
54 }