·  JavaScript – Syntax – Terms – Exception

 

- Info:

  - This tutorial shows basic exception handling in JavaScript.

 

- Catch:

  - This example shows how t catch Exception.

  - In this example we have misspeld alert() as alert123() which will throw an Exception.

  - Create D\Temp\JavaScript\Test.html

 

    Test.html

    <script> 

   

      try {

        alert123("Hello.");

      }

      catch(err) {

        document.write(err.message);

      }

   

    </script>

 

    output

    alert123 is not defined

 

- Throw:

  - This example shows how tt throw Exception.

  - Thrown exception can be: variable, array or object.

    Since built in Exceptions are objects with message property you should try to throw such objects.

  - Create D\Temp\JavaScript\Test.html

 

    Test.html

    <script> 

   

      try {

        throw { message:"Ups" };      //Throw object as exception

      }

      catch(err) {

        document.write(err.message);

      }

   

    </script>

 

    output

    Ups

 

- Identify Exception Type:

  - To identify Exception type you have to anylize caught Exception.

  - This is in contrast to Java where you can have multiple catch blocks each catching different type of Exception.

  - Create D\Temp\JavaScript\Test.html

 

    Test.html

    <script> 

   

      try {

        //throw { message:"type1" };      //Throw object as exception

        //throw { message:"type2" };      //Throw object as exception

        alert123("Wronf function name");

      }

      catch(err) {

        if      (err.message=="type1") { document.write("Type 1 Exception         "); }

        else if (err.message=="type2") { document.write("Type 2 Exception         "); }

        else                           { document.write("Unknown Type of Exception"); }

      }

   

    </script>