1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
| import java.io.File; import java.io.FileInputStream; import java.util.Date; import java.util.Scanner;
下例为编译时异常: public void test7(){ File file = new File("hello.txt"); FileInputStream fis = new FileInputStream(file); int data = fis.read(); while(data != -1){ System.out.print((char)data); data = fis.read(); } fis.close(); } 下例运行时异常: 1:AirthmeticExctption 算数异常:
public void test6(){ int a = 10; int b = 0; System.out.println(a / b); }
2:InputMismatchException 输入类型不匹配异常:
public void test5(){ Scanner scanner = new Scanner(System.in); int score = scanner.nextInt(); System.out.println(score); scanner.close(); }
3:NumberFormatException 数字格式异常:
public void test4(){ String str = "123"; str = "abc"; int num = Integer.parseInt(str); }
4:ClassCastException 类型转换异常:
public void test3(){ Object obj = new Date(); String str = (String)obj; }
5:IndexOutOfBoundsException 数组下标越界异常:
public void test2(){
String str = "abc"; System.out.println(str.charAt(3)); }
6:NullPointerException 空指针异常:
public void test1(){
String str = "abc"; str = null; System.out.println(str.charAt(0)); } }
|