• Uncategorized

Daily Tip: Exception handling in JavaScript

Exception handling is not much used while writing code in JavaScript. Lack of which leads to the error in one function and thereby the whole page stops functioning. 

Techniques to handle exception are listed below with examples

  • Using try..catch block

Like the regular C# try… catch block, the JavaScript code will be placed in the try block with all exceptions caught in the catch block as shown below:

Example:

   1:  function DivideNumbers(var numberValue, var divisor)
   2:  {
   3:      try
   4:      {
   5:           var answer = numberValue/divisor
   6:      }
   7:      catch(err)
   8:      {
   9:           document.write(err.name + ": " + err.message + " <br />");
  10:      }
  11:  }
  12:   

Note: finally block can also be used.

  • Using onerror event

On error event is raised when an exception occurs in any JavaScript function. It is similar to the Application_Error of Asp.Net. The below example shows to provide event handler for the on error event

Example:

   1:  window.onerror = function(errorMessage, fileName, lineNumber)
   2:  {
   3:      document.write('Error Message: ' + errorMessage);
   4:  }

Deepak Kamboj

Deepak Kamboj is a Solution Architect and Technology Enthusiast, located at Redmond, WA, having 14+ years of hands on experience in the IT industry.

You may also like...