Cleanup Counter with Finally
JavaScript
Medium
3 views
Problem Description
Input has n and failAt. Simulate opening a resource n times in loop and closing in finally. If i equals failAt, throw. Print final openCount (should be 0).
Input Format
One line: n failAt (1-based, 0 means never fail).
Output Format
One integer openCount.
Official Solution
const fs=require('fs');const [n,failAt]=fs.readFileSync(0,'utf8').trim().split(/\\s+/).map(Number);let open=0;try{for(let i=1;i<=n;i++){open++;try{if(failAt===i)throw new Error('FAIL');}finally{open--;}}process.stdout.write(String(open));}catch(e){process.stdout.write(String(open));}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!