user3037172
user3037172

Reputation: 587

Javascript - Exception/Error data type?

try {
  example.example = example;
}  catch (err) {
  TraceError.sysout("Error test!", err);
}

In this above code segment, I am forcing an error since example is not defined. I am learning javascript currently and was wondering if in javascript what type err would be. Is there an Error object or an Exception object in this language, and is there a way to get information about that err object so that I can print a detailed message in my .sysout method?

Upvotes: 4

Views: 3470

Answers (2)

Aayush Gaur
Aayush Gaur

Reputation: 104

JavaScript does have a standard built in Error object which can be used for creating and logging errors.

Instances to Error objects are thrown when run-time errors occur (JavaScript provides a few built in standard error types). You can also use the error object as a base objects for 'user-defined exceptions'.

You can refer the following link for the complete documentation:

'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error'

Hope the answer helps.

(Also by looking at the code in the try block in the question, I assumed that you are familiar with object oriented programming.)

Upvotes: 0

Mhammad Chehab
Mhammad Chehab

Reputation: 93

use console.log or console.dir

 try {
     example.example = example;
  }  catch (err) {
    console.dir(err);
    console.log("Error Message!", err.message);
    console.log("Stack Trace" , err.stack);
 }

In this case if you check out your console you will notice that the error type is "ReferenceError".

Hence, every exception has a type.

Try to do this and you'll get the following:

 var x = undefined;
 x.myproperty= 0
 TypeError: Cannot set property 'myproperty' of undefined

 myfaultySyntax'
 SyntaxError: Unexpected token ILLEGAL

And so on! hopes this helps and gives you an idea.

Upvotes: 3

Related Questions