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:  }

  • Permanent link to this post Permalink 
  • Share this post! Share It! 
  • View this post's comments Comments (82) 
  • RSS Feed for this post's comments Comment RSS
  •    


About Me

Deepak Kamboj

Deepak Kamboj, MCTS, JCP
ASP.NET/C# Web Developer
Chandigarh, India

RSS Contact Twitter Facebook LinkedIn

Yahoo: DeepakKamboj@yahoo.com
GTalk: DeepakKamboj@gmail.com
Skype: DeepakKamboj

Recent Comments