1 packagecom.yhqtv.demo01Exception;2 /*
3 * 一、异常体系结构4 *java.lang.Throwable5 * ------java.lang.Error:一般不编写针对性的代码进行处理。6 * ------java.lang.Exception:可以进行异常的处理7 * ----------编译时异常(checked)8 * -------IOException9 * ----------FileNotFoundException10 * -------ClassNotFoundException11 * ----------运行时异常(unchecked)12 * --------NullPointerException13 * --------ArrayIndexOutOfBoundsException14 * --------ClassCastException15 * --------NumberFormatException16 * --------InputMismatchException17 * --------ArithmeticException18 *19 *面试题,常见的异常都有哪些?举例说明20 **/
21
22 importorg.junit.Test;23
24 importjava.io.File;25 importjava.io.FileInputStream;26 importjava.util.Date;27 importjava.util.Scanner;28
29 public classExceptionTest {30 //##################以下是编译时异常########################
31 @Test32 public voidtest7(){33 File file=new File("hello.txt");34 FileInputStream fis=newFileInputStream(file);35
36 int data=fis.read();37 while (data!=-1) {38 System.out.println((char) data);39 data =fis.read();40
41 }42 fis.close();43
44 }45 //##################以下是运行时异常########################46 //ArithmeticException
47 @Test48 public voidtest6(){49 int a=10;50 int b=0;51 System.out.println(a/b);52
53 }54 //InputMismatchException
55 @Test56 public voidtest5(){57 //Scanner sc=new Scanner(System.in);58 //int nextInt = sc.nextInt();
59 }60 //NumberFormatException
61 @Test62 public voidtest4(){63 String str="123";64 str="abc";65 int i =Integer.parseInt(str);66 }67
68 //ClassCastException
69 @Test70 public voidtest3(){71 Object obj=newDate();72 String str=(String)obj;73
74 }75
76 //ArrayIndexOutOfBoundsException
77 @Test78 public voidtest2(){79 //int[] arr=new int[3];80 //System.out.println(arr[6]);
81
82 String str="abc";83 System.out.println(str.charAt(3));84
85 }86
87
88 //NullPointerException
89 @Test90 public voidtest1(){91 //int[] arr=null;92 //System.out.println(arr[3]);
93
94 String str="abc";95 str=null;96 System.out.println(str.charAt(3));97 }98
99 }