continuation icon indicating copy to clipboard operation
continuation copied to clipboard

Bizarre behavior when throw exceptions without try in a continuation block

Open BYVoid opened this issue 11 years ago • 1 comments

var test = function(callback) {
    console.log('called');
    callback(null);
}

function main() {
    try {
        test(obtain(a));
    } catch (e) {
        console.log('error by obtain', e);
    }
    throw 'a';
}

try {
    main();
} catch (e) {
    console.log('error by main', e);
}

Expected:

called
error by main a

Actual:

called
error by obtain a
error by obtain a
error by main a

BYVoid avatar Jun 09 '13 08:06 BYVoid

The problem seems that 1 try-catch block can generate 2 potentially nested try-catch blocks.

A somewhat hacky solution could be to add a boolean variable that tells whether one of the try-catch blocks have been triggered yet. If it has been triggered then the exception should be re-thrown.

So the example should compile to something like this:

function (_$cont) {
  var _$has_catched = false;
  try {
    test(function (arguments, _$param0, _$param1) {
      try {
        _$err = _$param0;
        a = _$param1;
        if (_$err)
          throw _$err;
        _$cont();
      } catch (_$err) {
        if (_$has_catched)
          throw _$err;
        _$has_catched = true;
        _$cont(_$err);
      }
    }.bind(this, arguments));
  } catch (_$err) {
    if (_$has_catched)
      throw _$err;
    _$has_catched = true;
    _$cont(_$err);
  }
}

reynir avatar Oct 04 '13 20:10 reynir