-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExceptionTest.java
More file actions
85 lines (70 loc) · 2.08 KB
/
Copy pathExceptionTest.java
File metadata and controls
85 lines (70 loc) · 2.08 KB
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
package random.java;
import org.junit.Test;
import java.util.Date;
import java.util.Scanner;
public class ExceptionTest {
/****************** 以下是编译时异常 checked ******************/
// @Test
// public void test7(){
// File file = new File("test.txt");
// FileInputStream fis = new FileInputStream(file);
//
// int data = fis.read();
// while (data!= -1){
// System.out.println((char) data);
// fis.read();
// }
// }
/****************** 以下是运行时异常 unchecked, RuntimeException ******************/
@Test
public void test1(){
/* NullPointerException */
int[] arr = null;
System.out.println(arr[0]);
}
/* IndexOutOfBoundsException */
@Test
public void test2(){
/* ArrayIndexOutOfBoundsException */
// int[] arr = new int[5];
// System.out.println(arr[5]);
/* StringIndexOutOfBoundsException */
String str = "hello";
System.out.println(str.charAt(10));
}
/* ClassCastException */
@Test
public void test3(){
// convert string to int
String numStr = "123";
int x = Integer.parseInt(numStr);
System.out.println(x); // return a primitive int
int y = Integer.valueOf(numStr);
System.out.println(y); // returns a Integer() object;
Object target = new Date();
String str = (String) target;
System.out.println(str);
}
/* NumberFormatException */
@Test
public void test4(){
String str = "10A";
int x = Integer.valueOf(str);
System.out.println(x);
}
/* InputMisMatchException */
@Test
public void test5(){
Scanner scanner = new Scanner(System.in);
int x = scanner.nextInt(); // if user's input is not an integer, will pop up the exception
System.out.println(x);
scanner.close();
}
/* ArithmeticException */
@Test
public void test6(){
int a = 9;
int b = 0;
System.out.println(a / b);
}
}