Skip to content

Commit ce48e3b

Browse files
committed
Error Handling
1 parent c24092d commit ce48e3b

File tree

2 files changed

+84
-0
lines changed

2 files changed

+84
-0
lines changed

12. Error Handling/index.html

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8">
5+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
6+
<title>Document</title>
7+
</head>
8+
<body>
9+
<h1 id="showMessage"></h1>
10+
<!-- link javacript file -->
11+
<script src="js/script.js"></script>
12+
13+
</body>
14+
</html>

12. Error Handling/js/script.js

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
// JavaScript Errors
2+
// Throw, and Try...Catch...Finally
3+
// The try statement defines a code block to run (to try).
4+
// The catch statement defines a code block to handle any error.
5+
// The finally statement defines a code block to run regardless of the result.
6+
// The throw statement defines a custom error.
7+
8+
// Errors Will Happen!
9+
// When executing JavaScript code, different errors can occur.
10+
// Errors can be coding errors made by the programmer, errors due to wrong input, and other unforeseeable things.
11+
12+
// In this example we misspelled "alert" as "adddlert" to deliberately produce an error:
13+
14+
// If we add try catch block the program run before and after error occurs. But not use try catch where an be possible to cause error next programm can not be run
15+
16+
17+
console.log("Bismillah");
18+
try {
19+
addAlert("Welcome Guest!");
20+
}catch(err){
21+
console.log(err.message);
22+
}
23+
24+
console.log("Hi thank you");
25+
26+
27+
// The throw Statement
28+
// The throw statement allows you to create a custom error.
29+
// Technically you can throw an exception (throw an error).
30+
// The exception can be a JavaScript String, a Number, a Boolean or an Object:
31+
32+
let input = prompt("Enter a Number: ");
33+
34+
try{
35+
if(input < 18) throw "To Young";
36+
else if(input > 100) throw "You do not need to vote! Rest in House";
37+
}catch(err){
38+
console.log(err);
39+
}
40+
41+
// The finally Statement
42+
// The finally statement lets you execute code, after try and catch, regardless of the result:
43+
44+
45+
// Syntax
46+
// try {
47+
// Block of code to try
48+
// }
49+
// catch(err) {
50+
// Block of code to handle errors
51+
// }
52+
// finally {
53+
// Block of code to be executed regardless of the try / catch result
54+
// }
55+
56+
try{
57+
addAlert("");
58+
}catch(err){
59+
console.log(err.message);
60+
}finally{
61+
console.log("Do't Care Error or NOt");
62+
}
63+
64+
try{
65+
console.log("Finally Check");
66+
}catch(err){
67+
console.log(err.message);
68+
}finally{
69+
console.log("Do't Care Error or NOt");
70+
}

0 commit comments

Comments
 (0)