Page 162 - CITS - Computer Software Application -TT
P. 162

COMPUTER SOFTWARE APPLICATION - CITS




           Syntax
           try {
             Block of code to try
           }
           catch(err) {

             Block of code to handle errors
           }
           finally {
             Block of code to be executed regardless of the try / catch result

           }
           Example
           function myFunction() {
             const message = document.getElementById(“p01”);
             message.innerHTML = “”;

             let x = document.getElementById(“demo”).value;
             try {
               if(x.trim() == “”) throw “is empty”;
               if(isNaN(x)) throw “is not a number”;
               x = Number(x);

               if(x > 10) throw “is too high”;
               if(x < 5) throw “is too low”;
             }
             catch(err) {
               message.innerHTML = “Error: “ + err + “.”;

             }
             finally {
               document.getElementById(“demo”).value = “”;
             }

           }
           The Error Object
           JavaScript has a built in error object that provides error information when an error occurs.
           The error object provides two useful properties: name and message.
           Error Object Properties

               Property                                         Description
               name                                             Sets or returns an error name
               message                                          Sets or returns an error message (a string)
           Error Name Values
           Six different values can be returned by the error name property:






                                                           149

                             CITS : IT&ITES - Computer  Software Application - Lesson 37 - 46
   157   158   159   160   161   162   163   164   165   166   167