Falsy Values And Error Handling in JavaScript

 Falsy Values:

       The following values evaluates to false, known as Falsy values.

      • false 
      • undefined
      • NaN(Not a Number)
      • 0(zero)
      •  null
      •  empty string('')

Note: All other values except above values are called truthy values and evaluates to true.


Exception Handling:

       Exception is an event which interrupts the normal flow of the program execution. It may occur due to some programming mistake or any unidentified errors.

We can handle exceptions in JavaScript using try...catch block.

Let's understand it with an example;

      let arr =[1,2,3]
      try{
         //statements in which exception could occur 
       int idx = 5
       if(arr[idx] === undefined){
             throw "Array index out of bounds or value is undefined"
      }
      console.log("value :"+arr[idx])
     }catch(error){
             //Handle exception here.  
            console.error(error)
     }

Note: throw keyword is used to throw an exception. The value thrown using throw keyword could be any valid data type.
       - you can have any number of catch associated with a try block.


Finally block:

        try...catch...finally, finally block statements execute after try and catch block. It will always execute whether the exception occurs or not.

Note: It is basically used to close the resources.
        - If try block returns a value, then value returned by try or catch blocks will be overridden with the return value of finally block.

         Example:

               try{
                    openFile(filename)
                    writeFile(data)
               }
               catch(error){
                    //handle error
               }
               finally{
                    closeFile()
              }


You can throw more appropriate errors using Error object by passing a message into it as 

             try{
                  throw new Error("error message")
            }catch(e){
                 console.log(e.message); //error message
           }


Continue Learning: Loops in JavaScript



Comments

Popular Posts