forked from smartherd/DartTutorial
-
Notifications
You must be signed in to change notification settings - Fork 1
/
18_exception_handling.dart
71 lines (62 loc) · 1.58 KB
/
18_exception_handling.dart
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
// OBJECTIVE: Exception Handling
// 1. ON Clause
// 2. Catch Clause with Exception Object
// 3. Catch Clause with Exception Object and StackTrace Object
// 4. Finally Clause
// 5. Create our own Custom Exception
void main() {
print("CASE 1");
// CASE 1: When you know the exception to be thrown, use ON Clause
try {
int result = 12 ~/ 0;
print("The result is $result");
} on IntegerDivisionByZeroException {
print("Cannot divide by Zero");
}
print(""); print("CASE 2");
// CASE 2: When you do not know the exception use CATCH Clause
try {
int result = 12 ~/ 0;
print("The result is $result");
} catch (e) {
print("The exception thrown is $e");
}
print(""); print("CASE 3");
// CASE 3: Using STACK TRACE to know the events occurred before Exception was thrown
try {
int result = 12 ~/ 0;
print("The result is $result");
} catch (e, s) {
print("The exception thrown is $e");
print("STACK TRACE \n $s");
}
print(""); print("CASE 4");
// CASE 4: Whether there is an Exception or not, FINALLY Clause is always Executed
try {
int result = 12 ~/ 3;
print("The result is $result");
} catch (e) {
print("The exception thrown is $e");
} finally {
print("This is FINALLY Clause and is always executed.");
}
print(""); print("CASE 5");
// CASE 5: Custom Exception
try {
depositMoney(-200);
} catch (e) {
print(e.errorMessage());
} finally {
// Code
}
}
class DepositException implements Exception {
String errorMessage() {
return "You cannot enter amount less than 0";
}
}
void depositMoney(int amount) {
if (amount < 0) {
throw new DepositException();
}
}