Exceptions in javascript, should they be used and how?

I have been told several times that it is "bad" to use exceptions in javascript. It was not actually said why this is bad, but, on the contrary, I have to use the gap, continue and return instead.

This is normal, except that I do not need to return / interrupt / continue, I need to quit. I have a case where I have iterator functions nested inside each other, each of which returns the next value when called, so I use an exception to indicate that there is nothing more to iterate: it seems like a logical way to do this, makes the code clean and works great in practice. Is there any reason not to use exceptions in js?

The second question, when I use exceptions, what objects should I throw? For errors, I obviously throw Error instances, but for special cases (stop iteration, etc.) I needed a quick way to check for these exceptions, and what I did just define an empty named function (StopIteration () { }), and since the functions are compared by reference, I can always check if this is really my special case, or I just have to rebook. Is there a better or more idotic way to do this in js? Should I try to reorganize my code, do not use exceptions?

thank

+5
source share
4 answers

hasNext isEmpty (, undefined), ,

//with hasNext
while(it.hasNext()){
var val = it.next();
//...
}
//or with a sentinal undefined
while( (val = it.next()) !== undefined){
//...
}
+2

, , , . , , "catch" , .

, () , ( ). :

function findValueInMatrix(value, matrix) {
  var r, c, coords, rows=matrix.length, cols=matrix[0].length;
  found: // Label the outer loop as "found" so we can break from it.
  for (r=0; r<rows; r++) {
    for (c=0; c<cols; c++) {
      if (matrix[r][c] == value) {
        coords = [r, c]
        break found; // Exit the loop labeled "found".
      }
    }
  }
  return coords;
}

.

jsPerf , , ( ).

+3

, , , - ; .

, , , , . (, , ), . , StopIteration , .

https://developer.mozilla.org/en/JavaScript/Guide/Iterators_and_Generators ( ). , .

0

/ - .

, , node, ..

node, ( ), , . , , , "" . - , , , .

( ) -.

-1

All Articles