Javascript - Exception


exception in Javascript

Exception can be catched:

  • in a try, catch, throw, finally statement.
  • with the catch function with a promise. See catch


With the error object

try {
  throw new Error('Badddd')
} catch (e) {
  if (e instanceof Error) {
    // you should use `console.error`
    console.log( + ': ' + e.message + ". Stack Trace" + e.stack)

With a string

You can also throw a string. You don't get extra information such as the stack trace but it's possible.

try {
  throw 'Badddd'
} catch (e) {


The interface of an error is

interface Error {
    name: string;
    message: string;
    stack?: string;



type (instanceof)

Javascript - instanceof An error is an object, to discover the instance, just output the prototype name

try {
	// an error occured
} catch (e){
    console.log("The instance of the error is "+e.__proto__.toString()); // To get the instance of name
    // if e.__proto__.toString() ==> SyntaxError
    if (e instance SyntaxError) {
       //... Do whatever

Variable scope

The try…catch binds a caught exception to a variable that is scoped just to the catch block (not on the function level). This is the only scope exception.

var foo = "initial value";
try {
	throw "exception";
} catch (foo) { //  < -- The local variable foo is a caught exception and will not affect the local variable because its scope is limited to the try catch block
	foo = "exception"; // <-- This change is only for the try block

console.log("The foo variable was not polluted when declared as a caught exception\n"+
  "foo will still have its initial value");

Caugth with Google Analytics

Powered by ComboStrap