forked from Swap76/Learn-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtry_and_catch.js
More file actions
71 lines (52 loc) · 1.57 KB
/
Copy pathtry_and_catch.js
File metadata and controls
71 lines (52 loc) · 1.57 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
//Try and Catch
/* In JavaScript, try/catch/finally** statement handle errors that may occur in the block.
try statement eables you to test your code in the block.
catch statement enables you to execute a block of code when it catches an error.
finally statement enables you to execute always after try and catch, regardless of an exception was thrown or caught.
*/
// Syntax
try {
throw 'exception'; // generate an exception
} catch (error) {
// statements to handle any exceptions
} finally {
// always runs regardless of the resulf ot try/catch
}
// Errors
// Reference Error
try {
hello(); // hello is not defined so it will cause a reference errorr
} catch (error) {
console.log(error);
} finally {
console.log('Finally runs reguardess of the reuslt');
}
// Type Error
try {
null.hello(); // hello is not defined so it will cause a reference errorr
} catch (error) {
console.log("You cannot call from null");
} finally {
console.log('Finally runs reguardess of the reuslt');
}
// Syntax Error
try {
eval('2+2'); // thsi works fine
eval('Hello, World!'); // this will generate error
} catch (error) {
console.log("Syntax error");
} finally {
console.log('Finally runs reguardess of the reuslt');
}
// User Defined Error
const person = {name:John, age: 23};
try {
if(!person.gender){
// throw 'person has no gender'
throw new SyntaxError('Person has no gender');
}
} catch (error) {
console.log("You cannot call from null");
} finally {
console.log('Finally runs reguardess of the reuslt');
}