Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exceptions in javascript, should I use them and how?

I've been told a few times that it's "bad" to use exceptions in javascript. Haven't really been told why it's bad, but inestead that I should use break, continue and return instead.

Which is fine, except I don't need to return/break/continue, I need to throw. I have a case where I have iterator functions nested in each other, each one returns the next value on call, so I use an exception to indicate that there's nothing more to iterate : seems like a logical way to do it, makes the code clean and works perfectly in practice. Is there really any reason not to use exceptions in js?

Second question, when I'm using exceptions, what kind of objects should I throw? For errors I'll obviously throw instances of Error, but for special cases (stop iteration, etc) I needed a quick way to check for those specific exceptions, and what I did is simply define an empty named function (function StopIteration(){}) and since functions are compared by reference I can always check if it's my special case or I should just rethrow. Is there a better or more idomatic way to do this in js? Should I really try to refactor my code avoid using exceptions?

Thank you

like image 406
fingerprint211b Avatar asked May 26 '11 14:05

fingerprint211b


People also ask

When should exceptions be used?

Exceptions should be used for situation where a certain method or function could not execute normally. For example, when it encounters broken input or when a resource (e.g. a file) is unavailable. Use exceptions to signal the caller that you faced an error which you are unwilling or unable to handle.

Should we always use exceptions?

As a general rule of thumb, throw an exception when your program can identify an external problem that prevents execution. If you receive data from the server and that data is invalid, throw an exception.

What are exceptions and how do we handle it?

Exception handling is the process of responding to unwanted or unexpected events when a computer program runs. Exception handling deals with these events to avoid the program or system crashing, and without this process, exceptions would disrupt the normal operation of a program.


1 Answers

It sounds like you're searching through a multidimensional space using nested loops, which is a fairly common thing to program. It's tempting to throw an exception from the innermost loop when the target is found which then gets caught by a "catch" block around the outermost loop but this often considered poor practice.

Language designers are aware of this pitfall so they allow us to give labels (names) to loop structures so that we can break from them (or continue to them). Consider this example:

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

You can find more information in this post about breaking from nested loops.

This jsPerf test case also demonstrates that breaking to a label is nominally faster than throwing an exception (presumably in most browsers).

like image 156
maerics Avatar answered Nov 14 '22 23:11

maerics