35-异常

1. 异常的体系结构
* java.lang.Throwable
* |-----java.lang.Error:一般不编写针对性的代码进行处理。
* |-----java.lang.Exception:可以进行异常的处理
*   |------编译时异常(checked)
*     |-----IOException
*        |-----FileNotFoundException
*     |-----ClassNotFoundException
*    |------运行时异常(unchecked,RuntimeException)
*     |-----NullPointerException
*     |-----ArrayIndexOutOfBoundsException
*     |-----ClassCastException
*        |-----NumberFormatException
*     |-----InputMismatchException
*        |-----ArithmeticException

2.从程序执行过程,看编译时异常和运行时异常

编译时异常:执行javac.exe命名时,可能出现的异常
运行时异常:执行java.exe命名时,出现的异常

3.常见的异常类型,举例说明:

 1 //******************以下是运行时异常***************************
 2 //ArithmeticException
 3 @Test
 4 public void test6(){
 5     int a = 10;
 6     int b = 0;
 7     System.out.println(a / b);
 8 }
 9 
10 //InputMismatchException
11 @Test
12 public void test5(){
13     Scanner scanner = new Scanner(System.in);
14     int score = scanner.nextInt();
15     System.out.println(score);
16 
17     scanner.close();
18 }
19 
20 //NumberFormatException
21 @Test
22 public void test4(){
23     String str = "123";
24     str = "abc";
25     int num = Integer.parseInt(str);
26 }
27 
28 //ClassCastException
29 @Test
30 public void test3(){
31     Object obj = new Date();
32     String str = (String)obj;
33 }
34 
35 //IndexOutOfBoundsException
36 @Test
37 public void test2(){
38     //ArrayIndexOutOfBoundsException
39     // int[] arr = new int[10];
40     // System.out.println(arr[10]);
41     //StringIndexOutOfBoundsException
42     String str = "abc";
43     System.out.println(str.charAt(3));
44 }
45 
46 //NullPointerException
47 @Test
48 public void test1(){
49     // int[] arr = null;
50     // System.out.println(arr[3]);
51 
52     String str = "abc";
53     str = null;
54     System.out.println(str.charAt(0));
55 }
56 
57 //******************以下是编译时异常
58 @Test
59 public void test7(){
60 // File file = new File("hello.txt");
61 // FileInputStream fis = new FileInputStream(file);
62 // 
63 // int data = fis.read();
64 // while(data != -1){
65 // System.out.print((char)data);
66 // data = fis.read();
67 // }
68 // 
69 // fis.close();
70 
71 }

补充:

原文地址:https://www.cnblogs.com/shici/p/13353999.html