Unit 4 - JavaScript (Error Handling & JSON)

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 29

Unit 4: Client side Scripting

Topics Covered

Error Handling

JSON
❑ JSON Syntax
❑ Sending, receiving and storing data.

1
JavaScript Errors
When executing JavaScript code, different errors can occur. The types
of errors can be classified as:

Syntax Errors

Runtime Errors

Logical Errors

2
Syntax Errors
• Syntax errors, also called parsing errors, occur at compile time in traditional
programming languages.
• It is an error in the syntax of a sequence of characters or tokens that is
intended to be written in a particular programming language or it is also the
compile-time error if the syntax is not correct then it will give an error
message.

3
Runtime Errors
• A runtime error is an error that occurs during the execution of the program,
also known as the exceptions.

4
Logical Errors
• Logic errors can be the most difficult type of errors to be traced as it is the
error on the logical part of the coding or logical error is a bug in a program
that causes it to operate incorrectly and terminate abnormally (or crash).

5
JavaScript – Error handling
• Errors can be coding errors made by the programmer, errors due to
wrong input, and other unforeseeable things.

• Errors in Scripts can be handled using the:-


– try statement lets you test a block of code for errors.
– catch statement lets you handle the error.
– throw statement lets you create custom errors.
– finally statement lets you execute code, after try and catch,
regardless of the result.
6
JavaScript try and catch
• The try statement allows you to define a block of code to be tested for
errors while it is being executed.

• The catch statement allows you to define a block of code to be


executed, if an error occurs in the try block.

• The JavaScript statements try and catch come in pairs:

7
JavaScript Throws Errors
• When an error occurs, JavaScript will normally stop, and
generate an error message.
• The throw statement allows you to create a custom error.
• The technical term for this is: throw an exception.

8
finally Statement
• The finally statement lets you execute code, after try and
catch, regardless of the result:

9
JavaScript – Error handling Example 1
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Error Handling</h2>

<p>This example demonstrates how to use <b>catch</b> to display an error.</p>

<p id="demo"></p>

<script>
try {
adddlert("Welcome guest!");
}
catch(err) {
document.getElementById("demo").innerHTML = err.message;
}
</script>
</body>
</html>
10
JavaScript – Error handling Example 2
<!DOCTYPE html> let x = document.getElementById("demo").value;
<html> try {
<body> if(x == "") throw "empty";
<h2>JavaScript try catch throws</h2> if(isNaN(x)) throw "not a number";
<p>Please input a number between 5 and 10:</p>
x = Number(x);
<input id="demo" type="text">
if(x < 5) throw "too low";
<button type="button" onclick="myFunction()">Test
Input</button> if(x > 10) throw "too high";
<p id="p01"></p> }
<script>
catch(err) {
function myFunction() {
message.innerHTML = "Input is " + err;
const message = document.getElementById("p01");
message.innerHTML = ""; }
}</script></body></html>
11
JavaScript – Error handling Example 3
<!DOCTYPE html> let x = document.getElementById("demo").value;

<html> try {
<body> if(x == "") throw "is empty";
<h2>JavaScript try catch</h2> if(isNaN(x)) throw "is not a number";
<p>Please input a number between 5 and 10:</p> x = Number(x);
<input id="demo" type="text">
if(x > 10) throw "is too high";
<button type="button" onclick="myFunction()">Test
Input</button> if(x < 5) throw "is too low";
<p id="p01"></p> }
<script> catch(err) { message.innerHTML = "Input " + err; }
function myFunction() {
finally {
const message = document.getElementById("p01");
document.getElementById("demo").value = "";
message.innerHTML = "";
} } </script></body> </html>
12
JavaScript Object Notation - JSON
• JSON is a lightweight text-based open standard designed for
human-readable data interchange.
• The format was specified by Douglas Crockford.
• It has been extended from the JavaScript scripting language.
• The filename extension is .json.
• JSON Internet Media type is application/json.
• The Uniform Type Identifier is public.json.

13
Uses of JSON
● It is used while writing JavaScript based applications that includes
browser extensions and websites.
● JSON format is used for serializing and transmitting structured data over
network connection.
● It is primarily used to transmit data between a server and web
applications.
● Web services and APIs use JSON format to provide public data.
● It can be used with modern programming languages.
14
Characteristics of JSON
● JSON is "self-describing“ and easy to read and write.
● It is a lightweight text-based interchange format.
● JSON is language independent.

15
JSON SYNTAX
• JSON supports the following two data structures −

• Collection of name/value pairs − This Data Structure is supported by


different programming languages.

• Ordered list of values − It includes array, list, vector or sequence etc.

16
JSON SYNTAX
JSON syntax is derived from JavaScript object notation syntax.
• Data is represented in name/value pairs.
• Curly braces hold objects and each name is followed by ':'(colon), the
name/value pairs are separated by , (comma).
var person={"name":"John", "age":30, "car":null}

• Square brackets hold arrays and values are separated by ,(comma).


var person={"employees":["John", "Anna", "Peter"]}
17
JSON DATATYPES
In JSON, values must be one of the following data types:

• a string
• a number
• an object (JSON object)
• an array
• a Boolean 18

• null
JSON DATATYPES
JSON values cannot be one of the following data types:
• a function
• a date
• undefined

19
JSON.parse()

• A common use of JSON is to exchange data to/from a web server.

• When receiving data from a web server, the data is always a string.

• Parse the data with JSON.parse(), and the data becomes a JavaScript
object.

20
JSON.parse() Example

21
JSON.parse() Example
<!DOCTYPE html>
<html>
<body>

<h2>Creating an Object from a JSON String</h2>

<p id="demo"></p>

<script>
const txt = '{"name":"John", "age":30, "city":"New York"}'
const obj = JSON.parse(txt);
document.getElementById("demo").innerHTML = obj.name + ", " + obj.age;
</script>

</body>
</html>
22
JSON.stringify()
• When sending data to a web server, the data has to be a string.

• Convert a JavaScript object into a string with JSON.stringify().

23
JSON.stringify() Example

24
JSON.stringify() Example
<!DOCTYPE html>
<html>
<body>

<h2>Create a JSON string from a JavaScript object.</h2>


<p id="demo"></p>

<script>
const obj = {name: "John", age: 30, city: "New York"};
const myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;
</script>

</body>
</html>
25
STORING DATA
• When storing data, the data has to be a certain format, and regardless of
where you choose to store it, text is always one of the legal formats.

• JSON makes it possible to store JavaScript objects as text.

26
STORING DATA EXAMPLE

27
STORING DATA EXAMPLE
<!DOCTYPE html>
<html>
<body>
<h2>Store and retrieve data from local storage.</h2>
<p id="demo"></p>
<script>
// Storing data:
const myObj = { name: "John", age: 31, city: "New York" };
const myJSON = JSON.stringify(myObj);
localStorage.setItem("testJSON", myJSON);
// Retrieving data:
let text = localStorage.getItem("testJSON");
let obj = JSON.parse(text);
document.getElementById("demo").innerHTML = obj.name;
</script></body></html>
28
QUESTIONS
• List and explain the type of errors?
• Explain error handling in JavaScript with a code snippet.
• List/Explain uses of JSON.
• List/Explain characteristics of JSON.
• Explain storing of data in JSON with an example.
• List/Explain the methods for interchanging data in JSON with an example.
• Explain JSON.parse() method with a code snippet.
• Explain JSON.stringify() method with a code snippet.
29

You might also like