Javascript - Exception

1 - About

exception in Javascript

Exception can be catched:

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

2 - Example


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

3 - Syntax

The interface of an error is


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

4 - Management

4.1 - Pause

4.2 - 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
    }
}

4.3 - 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");
console.log(foo); 

4.4 - Caugth with Google Analytics


Data Science
Data Analysis
Statistics
Data Science
Linear Algebra Mathematics
Trigonometry

Powered by ComboStrap