Skip to content

9. Errors and exceptions

Image

JavaScript does not have a very sophisticated exception-handling system. However, it does provide the [throw] statement, which allows you to signal an error, as well as the try/catch/finally structure, which allows you to catch those errors.

9.1. script [excep-01]

In the following script, we will display the current date in the format [hours:minutes:seconds:milliseconds]. To do this, we will use a JavaScript library called [moment.js]. We install it, as usual, using the [npm] tool:

Image

The script code is as follows:


'use strict';
 
// package moment
import moment from 'moment';
 
...

To understand how to write the [import] line on line 4, we can look at the definition of the [moment] module:

Image

  • in [1-2], we go to the module definition;
  • in [3], we have a TypeScript file, not a JavaScript file. At runtime, this TypeScript file is compiled into a JavaScript file before being used;
  • in [4], we search for the [export] statements (Ctrl-F);
  • in [5], the statement exports the [moment] object. This can be imported in ES6 as follows:

import moment from 'moment';

You can use any name to import the [moment] object, for example:


import m from 'moment';

Let’s go back to the script code:


'use strict';
 
// package moment
import moment from 'moment';
 
// try / catch / finally principle
for (let i = 0; i < 10; i++) {
  // date - current time
  const now = Date.now();
  // format time to get milliseconds
  const time = moment(now).format("HH:mm:ss:SSS");
  // milliseconds
  const milli = Number(time.substr(time.length - 3));
  // display
  console.log("--------------------itération n° ", i, "à", time);
  try {
    // number varies according to time of day
    const nbre = milli % 2;
    if (nbre === 0) {
      // launch an error msg
      throw "erreur";
    }
    // if we've arrived here, there's been no mistake
    console.log("pas d'erreur");
  } catch (error) {
    // if we get here, it's because there's been a mistake
    console.log("erreur1=", error);
  } finally {
    // executed in all cases error or not
    console.log("finally")
  }
}

Comments

  • line 4: import the [moment] library;
  • The script loops 10 times (line 7). On each loop iteration, the current time is retrieved in the format [hours:minutes:seconds:milliseconds] (lines 8–13);
  • if the number of milliseconds is even, an error message is displayed (lines 19–22);
  • The goal here is to understand how try / catch / finally works

Execution


[Running] C:\myprograms\laragon-lite\bin\nodejs\node-v10\node.exe -r esm "c:\Data\st-2019\dev\es6\javascript\exceptions\excep-01.js"
--------------------itération n° 0 à 17:57:04:440
erreur1= erreur
finally
--------------------itération n° 1 à 17:57:04:447
pas d'erreur
finally
--------------------itération n° 2 à 17:57:04:448
erreur1= erreur
finally
--------------------itération n° 3 à 17:57:04:448
erreur1= erreur
finally
--------------------itération n° 4 à 17:57:04:448
erreur1= erreur
finally
--------------------itération n° 5 à 17:57:04:448
erreur1= erreur
finally
--------------------itération n° 6 à 17:57:04:448
erreur1= erreur
finally
--------------------itération n° 7 à 17:57:04:448
erreur1= erreur
finally
--------------------itération n° 8 à 17:57:04:449
pas d'erreur
finally
--------------------itération n° 9 à 17:57:04:449
pas d'erreur
finally

We can see that the [finally] clause is always executed, whether there is an error or not.

9.2. script [excep-02]

This script demonstrates that the [throw] statement can throw any type of data and that this data is fully captured by the [catch] clause.


'use strict';
 
// you can "throw" just about anything to signal an error
let i = 0;
console.log("--------------------essai n° ", i);
// launch a string
try {
  throw "msg d'erreur";
} catch (error) {
  // there has been a mistake
  console.log("erreur=[", error, "], type=", typeof (error));
}
// launch a table
i++;
console.log("--------------------essai n° ", i);
try {
  throw [1, 2, 3]
} catch (error) {
  // there has been a mistake
  console.log("erreur=[", error, "], type=", typeof (error));
}
// launch a literal object
i++;
console.log("--------------------essai n° ", i);
try {
  throw { nom: "hercule", pays: "grèce antique" }
} catch (error) {
  // there has been a mistake
  console.log("erreur=[", error, "], type=", typeof (error));
}
// lancer un type Error
i++;
console.log("--------------------essai n° ", i);
try {
  throw new Error("erreur de connexion au réseau");
} catch (error) {
  // there has been a mistake
  console.log("erreur=[", error, "], type=", typeof (error));
}
// lancer un type Error
i++;
console.log("--------------------essai n° ", i);
try {
  throw new Error("erreur de connexion au réseau");
} catch (error) {
  // there has been an error - the message is in [error.message]
  console.log("erreur.message=[", error.message, "], type(error)=", typeof (error));
}

Comments

  • lines 35, 44: [Error] is a JavaScript class whose constructor accepts an error message as an optional first parameter. This message can be retrieved from the [Error.message] property (line 47);
  • There are other classes besides [Error] that can signal an error: [EvalError, InternalError, RangeError, ReferenceError, SyntaxError, TypeError, URIError);

Execution


[Running] C:\myprograms\laragon-lite\bin\nodejs\node-v10\node.exe -r esm "c:\Data\st-2019\dev\es6\javascript\exceptions\excep-02.js"
--------------------essai n° 0
erreur=[ msg d'erreur ], type= string
--------------------essai n° 1
erreur=[ [ 1, 2, 3 ] ], type= object
--------------------essai n° 2
erreur=[ { nom: 'hercule', pays: 'grèce antique' } ], type= object
--------------------essai n° 3
erreur=[ Error: erreur de connexion au réseau
at Object.<anonymous> (c:\Data\st-2019\dev\es6\javascript\exceptions\excep-02.js:35:9)
at Object.<anonymous> (c:\Temp\19-09-01\javascript\node_modules\esm\esm.js:1:251206)
at c:\Temp\19-09-01\javascript\node_modules\esm\esm.js:1:245054
at Generator.next (<anonymous>)
at bl (c:\Temp\19-09-01\javascript\node_modules\esm\esm.js:1:245412)
at kl (c:\Temp\19-09-01\javascript\node_modules\esm\esm.js:1:247659)
at Object.u (c:\Temp\19-09-01\javascript\node_modules\esm\esm.js:1:287740)
at Object.o (c:\Temp\19-09-01\javascript\node_modules\esm\esm.js:1:287137)
at Object.<anonymous> (c:\Temp\19-09-01\javascript\node_modules\esm\esm.js:1:284879)
at Object.apply (c:\Temp\19-09-01\javascript\node_modules\esm\esm.js:1:199341) ], type= object
--------------------essai n° 4
erreur.message=[ erreur de connexion au réseau ], type(error)= object

9.3. script [excep-03]

This script demonstrates that, within a [catch], you can distinguish the type of [Error] instance intercepted by the [catch]:


'use strict';
 
// package moment
import moment from 'moment';
 
// differentiate the Error instance received in a [catch]
for (let i = 0; i < 10; i++) {
  // date - current time
  const now = Date.now();
  // format time to get milliseconds
  const time = moment(now).format("HH:mm:ss:SSS");
  // milliseconds
  const milli = Number(time.substr(time.length - 3));
  console.log("--------------------itération n° ", i);
  try {
    // nbre [0, 1, 2]
    const nbre = milli % 3;
    switch (nbre) {
      case 0:
        throw new ReferenceError("erreur 1");
      case 1:
        throw new RangeError("erreur 2");
      default:
        throw new EvalError("erreur 3");
    }
  } catch (error) {
    // there has been a mistake
    if (error instanceof ReferenceError) {
      console.log("ReferenceError :", error.message);
    } else {
      if (error instanceof RangeError) {
        console.log("RangeError :", error.message);
      }
      else {
        if (error instanceof EvalError) {
          console.log("EvalError :", error.message);
        }
      }
    }
  }
}

Execution


[Running] C:\myprograms\laragon-lite\bin\nodejs\node-v10\node.exe -r esm "c:\Data\st-2019\dev\es6\javascript\exceptions\excep-03.js"
--------------------itération n° 0
ReferenceError : erreur 1
--------------------itération n° 1
RangeError : erreur 2
--------------------itération n° 2
RangeError : erreur 2
--------------------itération n° 3
RangeError : erreur 2
--------------------itération n° 4
RangeError : erreur 2
--------------------itération n° 5
RangeError : erreur 2
--------------------itération n° 6
EvalError : erreur 3
--------------------itération n° 7
EvalError : erreur 3
--------------------itération n° 8
EvalError : erreur 3
--------------------itération n° 9
EvalError : erreur 3