Page 184 - Computer Software Application TP - Volume 1
P. 184
COMPUTER SOFTWARE APPLICATION - CITS
EXERCISE 45 : Error Handling in JavaScript
Objectives
At the end of this exercise you shall be able to
• handle error using try - catch
• handle error using try - catch and throw
• handle error using try - catch finally.
Requirements
Tools/Materials
• Desktop / Laptop with latest configuration
• Text editor
• Web browser
Procedure
TASK 1: Error Handling using try-catch
1 Open the text editor
2 Write the following codes
<html >
<head>
<title> Object Literal Notation </title>
</head>
<body>
<script>
try
{
// Code that may throw an error
let x = 1;
let y = x + z; // z is not defined, this will throw an error
}
catch (error)
{
// Handle the error
console.error(“An error occurred:”, error.message);
}
</script>
</body>
</html>
3 Save the program as a .html file
4 Open the html file with a web browser
5 Go to the browsers console tab and verify the output.
169