-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherror_handling.js
More file actions
32 lines (28 loc) · 830 Bytes
/
error_handling.js
File metadata and controls
32 lines (28 loc) · 830 Bytes
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
// Error handling on JS using try/catch block.
function sqrRoot(x) {
try {
if (x == "") {
throw {message: "Can't square root Nothing"};
} else if (isNaN(x)) {
throw {message: "Can't square root a String"};
} else if (x < 0) {
throw {message: "Can't square root a Negative Number"};
}
return "sqrt(" + x + ") = " + Math.sqrt(x);
} catch (err) {
return err.message;
}
}
function writeIt() {
console.log(sqrRoot("Four"));
console.log(sqrRoot(""));
console.log(sqrRoot(-4));
console.log(sqrRoot(4));
}
writeIt();
// Try to assign to x an undefined variable named badVarName.
try {
var x = badVarName;
} catch (err) {
console.log(err.name + ': "' + err.message + '" occurred when assigning bad value to x.');
}