Javascript - Exception


This page is about exception in Javascript

Exceptions can be caught:

  • 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;

How to create another Exception Type?

export class SessionError extends Error {
throw new SessionError('Yolo');



Javascript Console Pause On Exception

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


Discover More
How to catch exceptions/errors in React?

This page is exception handling In React. When an non-catched javascript error occurs: React remove its UI (ie stop rendering the tree) from the screen. And show a special component known as error...
Javascript Lexical Environment Scope Chaine
Javascript - (Variable) Scope (Namespace)

Variable scope in Javascript. variable scope is delimited by the function definition, not a the block level A block has the scope of its inner function. As a function is also an object, by generalization,...
Javascript - Await and Async Syntax

await and async is the second promise syntax that permits to manipulate promise. The async/await syntax is part of ECMAScript 2017 and reduces the callback nesting find in the chaining syntax. The...
Javascript - Error

Javascript Test - Assertion library

assertion in Javascript assert module - Node.js’ built-in assert module shouldjs/should.jsshould.js - BDD style LearnBoost/expect.jsexpect.js - expect()...

Share this page:
Follow us:
Task Runner