Advertisement
Beginner JavaScript, Error Handling

What does the finally block do?

Short answer

finally always runs after try/catch, whether or not an error was thrown or caught, and even if the try block returns early — making it ideal for cleanup code that must always execute.

Save JavaScript mock interview
Advertisement
AModel answer
finally always runs after try/catch, whether or not an error was thrown or caught, and even if the try block returns early — making it ideal for cleanup code that must always execute.
function readFile() {
  openFile();
  try {
    return process();
  } finally {
    closeFile(); // always runs
  }
}
Real-world example
Ensuring a loading spinner is hidden whether an API call succeeds or fails.
Likely follow-ups
  • Does a return inside finally override a return from try?
Related topics