-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThrowExample.java
More file actions
56 lines (49 loc) · 1.5 KB
/
ThrowExample.java
File metadata and controls
56 lines (49 loc) · 1.5 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
package example.ExceptionExample;
public class ThrowExample {
public static void CheckPassword(String pwd) {
if (pwd.length()>=5 && pwd.length()<=8) {
System.out.println("Password is successful: " + pwd);
} else {
System.out.println("Password is fail: " + pwd);
throw new StringIndexOutOfBoundsException("the length of password is not suitable.");
}
}
public static void main(String[] args) {
String[] pwd = {"123456", "123456789", "1234567"};
for (int i=0; i<pwd.length; i++) {
try {
CheckPassword(pwd[i]);
} catch (Exception e) {
System.out.println("Error! " + e.getMessage());
// e.printStackTrace();
}
}
System.out.println("end of checking password.");
}
}
/**
* Throws template example.
*/
class ThrowTemplateExample {
// 基本架構
public void commonExample() {
try {
} catch (Exception e) {
// 處理異常
}
}
// 另一種寫法
public void otherMethodExample() throws ExceptionInInitializerError, Exception {
// 可能發生異常
}
public static void main(String[] args) {
try {
ThrowTemplateExample tte = new ThrowTemplateExample();
tte.otherMethodExample();
} catch (ExceptionInInitializerError e) {
// 處理異常
} catch (Exception e) {
// 處理異常
}
}
}