How do we throw and capture RangeError, ReferenceError, TypeError in JavaScript?

I was wondering if any of you tried to catch errors like RangeError, ReferenceError and TypeError using the JavaScript exception handling mechanism?

For example, for RangeError:

try {
var anArray = new Array(-1); 
// an array length must be positive

         throw new RangeError("must be positive!")
}
catch (error) {  
         alert(error.message);
         alert(error.name);
}
finally {
         alert("ok, all is done!");
}

In the case above, am I throwing a new RangeError object?

In my code example, the alert (error.message) does not display the user message, which should be positive.

What can I do to throw my own RangeError object (and ReferenceError, TypeError)?

Best.

+3
source share
2 answers

, , , . , (, , FIREfox, ) RangeError Error . , new Error("must be positive!"). .

+2

, JavaScript , -. , undefined.

:

if (typeof someArray[foo] !== "undefined") {
    //do stuff
} else {
    //do error handling
    //Here I'm just throwing a simple exception with nothing than a message in it.
    throw new Error('something bad happened');
}

, "TypeError". , .

+2

Source: https://habr.com/ru/post/1756141/


All Articles