Skip to content

Throw From Finally (ARCH3155)

Key typescript.logging.throw-in-finally · Severity error · Category logging

Throwing an exception inside a finally block masks any exception still in flight from the try body. The original error is lost and only the finally error propagates.

function writeReport(file: FileHandle, data: string) {
try {
file.write(data);
} finally {
file.close(); // if this throws, it masks the try exception
}
}
function writeReport(file: FileHandle, data: string) {
try {
file.write(data);
} finally {
try {
file.close();
} catch (closeErr) {
logger.warn("failed to close file", { closeErr });
}
}
}

Wrap cleanup code in finally with its own try/catch and log rather than propagate.