-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathTryCatchDemo.java
More file actions
94 lines (79 loc) · 2.84 KB
/
Copy pathTryCatchDemo.java
File metadata and controls
94 lines (79 loc) · 2.84 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
86
87
88
89
90
91
92
93
94
import java.util.Scanner;
public class TryCatchDemo {
public static void demoTryCatch() {
int a = 5;
int b = 0;
try {
int c = a / b;
System.out.println(c);
} catch (Exception e) {
System.out.println("Không thể chia 1 số cho 0. " + e.getMessage());
}
}
public static void demoTryFinally() {
int a = 5;
int b = 0;
try {
int c = a / b;
System.out.println(c);
} finally {
System.out.println("Khối lệnh này luôn được thực thi!!!");
}
}
public static void demoTryCatchFinally() {
int a = 5;
int b = 0;
try {
int c = a / b;
System.out.println(c);
} catch (Exception e) {
System.out.println("Không thể chia 1 số cho 0. " + e.getMessage());
} finally {
System.out.println("Khối lệnh này luôn được thực thi!!!");
}
}
//try catch lồng nhau: Khi có khối try-catch lồng trong một khối try khác
//SỬ dụng khi tình huống có thể phát sinh trong đó một phần của khối có thể gây ra lỗi
//và bản thân toàn bộ khối có thể gây ra lỗi khác.
//Trong trường hợp này, các exception cần được xử lý lồng nhau
public static void nestedTrycatch() {
try {
try {
System.out.println("going to divide");
int b = 39 / 0;
} catch (ArithmeticException e) {
System.out.println(e);
}
try {
int a[] = new int[5];
a[5] = 4;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e);
}
System.out.println("other statement");
} catch (Exception e) {
System.out.println("handeled");
}
System.out.println("normal flow..");
}
//Sử dụng nhiều khối catch
public static void multiCatchBlock() {
Scanner scanner = new Scanner(System.in);
boolean check = false;
while(!check) {
try {
System.out.println("Nhập tử số: ");
int numerator = Integer.parseInt(scanner.nextLine());
System.out.println("Nhập mẫu số: ");
int denominator = Integer.parseInt(scanner.nextLine());
int result = numerator/denominator;
System.out.println(result);
check = true;
}catch (ArithmeticException ex1){
System.out.println("Không thể chia một số cho 0");
}catch (NumberFormatException ex2){
System.out.println("Vui lòng nhập số");
}
}
}
}