Finally

2 snippets across 2 stacks — JavaScript, Python

JSJavaScript

try / catch / finally

JS · Error Handling
syntax
try { ... }
catch (error) { ... }
finally { ... }
example
function parseConfig(jsonString) {
  try {
    return JSON.parse(jsonString);
  } catch (error) {
    console.error("Invalid config JSON:", error.message);
    return {};
  } finally {
    console.log("Config parsing attempted.");
  }
}

const config = parseConfig('{"debug": true}');
console.log(config);
output
"Config parsing attempted."
{ debug: true }

Note finally always runs, whether the try succeeded or catch was triggered. It even runs if try or catch contains a return statement.

PYPython

else & finally

PY · Error Handling
syntax
try:
    ...
except:
    ...
else:
    ...
finally:
    ...
example
def safe_divide(a: float, b: float) -> float | None:
    try:
        result = a / b
    except ZeroDivisionError:
        print("Cannot divide by zero")
        return None
    else:
        print(f"Result: {result}")
        return result
    finally:
        print("Division attempted")

safe_divide(10, 3)
safe_divide(10, 0)
output
Result: 3.3333333333333335
Division attempted
Cannot divide by zero
Division attempted

Note else runs only when no exception occurred. finally always runs, even after return statements. Use else to keep the try block minimal.