Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions src/transformation/visitors/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,10 @@ export const transformTryStatement: FunctionVisitor<ts.TryStatement> = (statemen
returnedIdentifier,
lua.SyntaxKind.AndOperator
);
} else if (statement.finallyBlock) {
// try without catch, but with finally — need to capture error for re-throw
const errorIdentifier = lua.createIdentifier("____error");
result.push(lua.createVariableDeclarationStatement([tryResultIdentifier, errorIdentifier], tryCall));
} else {
// try without return or catch
result.push(lua.createExpressionStatement(tryCall));
Expand All @@ -155,6 +159,22 @@ export const transformTryStatement: FunctionVisitor<ts.TryStatement> = (statemen
result.push(...context.transformStatements(statement.finallyBlock));
}

// Re-throw error if try had no catch but had a finally
if (!statement.catchClause && statement.finallyBlock) {
const notTryCondition = lua.createUnaryExpression(
lua.cloneIdentifier(tryResultIdentifier),
lua.SyntaxKind.NotOperator
);
const errorIdentifier = lua.createIdentifier("____error");
const rethrow = lua.createExpressionStatement(
lua.createCallExpression(lua.createIdentifier("error"), [
lua.cloneIdentifier(errorIdentifier),
lua.createNumericLiteral(0),
])
);
result.push(lua.createIfStatement(notTryCondition, lua.createBlock([rethrow])));
}

if (returnCondition && returnedIdentifier) {
const returnValues: lua.Expression[] = [];

Expand Down
22 changes: 22 additions & 0 deletions test/unit/error.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,28 @@ test("multi return from catch->finally", () => {
.expectToMatchJsResult();
});

test("throw propagates through finally to outer catch", () => {
util.testFunction`
function thrower() {
try {
throw "Error";
} finally {
}
}

function caller() {
try {
thrower();
return "NoCatch";
} catch (e) {
return e;
}
}

return caller();
`.expectToMatchJsResult();
});

test("return from nested finally", () => {
util.testFunction`
let x = "";
Expand Down