I
I
Ivan S. Glushko2015-07-11 05:58:35
JavaScript
Ivan S. Glushko, 2015-07-11 05:58:35

Is it possible to get in object "e" (error) a variable with an error when using try catch?

Hello. Is it possible to get in object "e" (error) a variable with error "A" in catch? It implies going beyond the array, as a result, the variable gets the “undefined” property. I could be wrong, correct me if enough Svidomo.

var Map = [];
Map.length = 50;
try {
    var A = Map[j + 100];
    var B = Map[j + 10];
} catch(e) {
    throw e;
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
Konstantin Kitmanov, 2015-07-11
@k12th

Arrays in JS are dynamic, it is impossible to go beyond them. Catching undefined - well, ok, but what if the array contains undefined?
It's easier to ensure that the index does not exceed a given number, using a wrapper (wrapping the entire array or making a function to access):

var myArr = [1, 2, 3];
myArr.get = function (index) {
    if (index > this.length - 1) {
        throw new RangeError();
    } else {
        return this[index];
    }
}

S
Sergey Sergey, 2015-07-11
@hahenty

You can try to access some property in A that is inherent in the expected value type.
Something like:

var A = Map[j + 100];
//...
A.toExponential(); // здесь вылетит, если не число,
A.chatAt(0); // здесь вылетит, если не строка,

and other prototype methods for other types.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question