forked from pirple/Keeping-Up-With-the-Javascripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Exceptions.js
executable file
·121 lines (98 loc) · 1.85 KB
/
Exceptions.js
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
/*
* Exceptions
*
*/
// Throw your own exception
/*
- Use the throw statement to throw own exception
- You specify the expression containing the value to be thrown
e.g.: throw expression
- Can throw any expression
*/
const myObjException = {
toString: function() {
return "I am an object exception";
}
}
function MyException(message) {
this.message = message;
this.name = "My exception";
this.toString = function() {
return this.name + ": " + this.message;
}
}
// throw new MyException("Missing data");
// try...catch
// try {
// throw "Exception!";
// }
// catch(e) {
// console.log(e);
// }
let myNum = "Chris";
const myErrorLog = [];
function checkIfNum(num) {
if (isNaN(num)) {
throw "not a number!";
} else {
console.log("Yes, this is a number")
}
}
function errorHandler(e) {
myErrorLog.push(e);
}
try {
checkIfNum(myNum);
}
catch(catchID) {
errorHandler(catchID);
}
function MyString(string) {
if (typeof string === "string") {
this.value = string;
this.getValue = function() {
console.log("Your string: " + this.value + ".");
}
}
else {
throw new StringExceptionError(string);
}
}
function StringExceptionError(value) {
this.value = value;
this.message = "must be a string";
this.toString = function() {
return this.value + ": " + this.message;
}
}
function verifyString(s) {
let str;
try {
str = new MyString(s);
}
catch(e) {
if (e instanceof StringExceptionError) {
console.log("String exception: " + e);
}
else {
throw "Unknown error";
}
}
return str;
}
const a = verifyString("2313123");
function finallyExample() {
try {
console.log("Hi");
throw 'test';
}
catch(e) {
console.log(e);
throw "Boo!";
}
finally {
console.log("Can I run?");
return;
}
}
console.log(finallyExample());