LearnFrenzy
Sign in Take a free test

Error Handling · Error Handling Coding Problems · Question 9

Guarantee resource cleanup with finally in JavaScript Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 9 Back to Exercise

Write withConnection(work) that opens a (simulated) database connection, passes it to work, and always closes it – whether work succeeds, throws, or returns early – then show that no connection is left open.

Solution
main.js
let open = 0, nextId = 1;
function connect() {
  open++;
  const conn = { id: nextId++, query: (sql) => { if (sql.includes("DROP")) throw new Error("permission denied"); return 3; } };
  console.log(`  open #${conn.id}`);
  return conn;
}

function withConnection(work) {
  const conn = connect();
  try {
    return work(conn);
  } finally {
    open--;                                 // runs on return AND on throw
    console.log(`  close #${conn.id}`);
  }
}

for (const sql of ["SELECT * FROM quiz", "DROP TABLE quiz"]) {
  try {
    console.log(`${sql} → ${withConnection((c) => c.query(sql))} rows`);
  } catch (e) {
    console.log(`${sql} → error: ${e.message}`);
  }
}
console.log("connections still open:", open);

Output Verified by running it on Node.js

  open #1
  close #1
SELECT * FROM quiz → 3 rows
  open #2
  close #2
DROP TABLE quiz → error: permission denied
connections still open: 0

The "with resource" pattern centralises cleanup: callers cannot forget to close, and finally runs before the result or error reaches them – which is why "close" prints first.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links