Explain Exception Handling concept in Java Script.



Run time error handling is important in all programs. Many object oriented programming languages provide a mechanism for dealing with general classes of errors. The mechanism is called ‘Exception Handling’. An exception is a run time error. You must write robust code then your program will be able to handle them. An exception in object based programming is an object created dynamically at run time which gives an error and some information about it.

The great thing about exception is that you can define your own exception classes to include what exactly you need to handle in the  problem successfully. 

Throw:- An exception is an object it is created using a standard ‘new’ method. Once the exception object exists you need to do something with it. the only thing is throw the exception.

Eg:-     do
            If (an error happens)
            {
               Creates a new exception object throw the exception
            }

try, catch( ):- 

 When you have a block of code which might cause the creation of an exception you need to program some code to handle the exception if it should happen. The ‘try, catch’ mechanism is found in many programming languages not just in ‘Java script’ . the idea here is that your program is going to try to execute a block of statements. if an exception is thrown by any of these statements, execution of the whole block stops and the program looks for a catch statements to handle the exception.

Syntax:- try
                  {
                      Statement 1; Statements that cause exception;
                      Statement 2;
                      Statement 3;
                  }
               catch (Exception)
                 {
                    Handle the exception.
                 }

If statement 1 throws an exception, statement  2 and statement  3 will not be executed instead the program will move straight to the ‘catch’ block.

Program:-
 
      < html>
             < body>
                < script language = “ java script”>
                 var x = prompt (“enter a number between 0 to 5, “ “);
                 try
                {
                  if (x > 5)
                   throw “error1”;
                 else if (x < o)
                   throw “error2”;
                 document. write (“you entered”,+ x);
                 }

               catch(e)
                 {
                  if (e = = “error1”)
                    alert (“error ! you entered a large number”);
                  else if (e = = “error2”)
                   alert (“ error ! you entered a small number”);
                  }

                </script>
             </body>
       </html>

Related

Web Technology 9048188001349348865

Post a Comment

emo-but-icon

item