-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path9. exceptions.dart
64 lines (56 loc) · 1.53 KB
/
9. exceptions.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
/// Exceptions in Dart
/// Dart has a rich set of exceptions that are used to indicate errors.
/// The most common exception is the [Exception] class.
/// The [Exception] class is the base class for all exceptions.
/// The [Exception] class is used to indicate that an error has occurred.
void main(List<String> args) {
/// try-catch block
try {
// code that might throw an exception
} catch (error) {
// code that will be executed if an exception is thrown
}
/// try-catch-finally block
try {
// code that might throw an exception
} catch (error) {
// code that will be executed if an exception is thrown
} finally {
// code that will be executed regardless of whether an exception is thrown or not
}
/// throw an exception
// throw Exception("An exception has occurred");
/// try-catch block
try {
// Divided by zero
int result = 12 ~/ 0;
print("The result is $result");
} catch (error) {
print(error);
}
//! If don't use exception handling
//! int result = 12 ~/ 0;
//! print("The result is $result");
/// try-catch-finally block
try {
int result = 12 ~/ 0;
print("The result is $result");
} catch (error) {
print(error);
} finally {
print("This is finally block and is always executed");
}
depositMoney(int amount) {
if (amount < 0) {
throw "Amount can't be less than zero";
}
}
/// throw an exception
try {
depositMoney(-200);
} catch (error) {
print(error);
} finally {
print("Transaction completed");
}
}