Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Explain the finally Statement in JavaScript with examples.
The finally statement in JavaScript always executes after try and catch blocks, regardless of whether an error occurred or not. This makes it ideal for cleanup operations and code that must run in all scenarios.
Syntax
try {
// Code that may throw an error
} catch (error) {
// Handle error (optional)
} finally {
// Always executes
}
Example: Finally Block Always Executes
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Finally Statement Demo</title>
</head>
<body>
<h3>Finally Statement Example</h3>
<button onclick="testFinally()">Test Finally Block</button>
<div id="result"></div>
<script>
function testFinally() {
let resultDiv = document.getElementById('result');
resultDiv.innerHTML = '';
try {
resultDiv.innerHTML += 'Try: Attempting to access undefined variable<br>';
let value = undefinedVariable; // This will cause an error
} catch (error) {
resultDiv.innerHTML += 'Catch: Error caught - ' + error.message + '<br>';
} finally {
resultDiv.innerHTML += 'Finally: This always executes!<br>';
}
}
</script>
</body>
</html>
Example: Finally Without Error
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Finally Without Error</title>
</head>
<body>
<h3>Finally Block - No Error Scenario</h3>
<button onclick="testSuccess()">Test Success Case</button>
<div id="output"></div>
<script>
function testSuccess() {
let outputDiv = document.getElementById('output');
outputDiv.innerHTML = '';
try {
outputDiv.innerHTML += 'Try: Code executed successfully<br>';
let result = 10 + 20;
outputDiv.innerHTML += 'Try: Result = ' + result + '<br>';
} catch (error) {
outputDiv.innerHTML += 'Catch: This won't execute<br>';
} finally {
outputDiv.innerHTML += 'Finally: Cleanup operations completed<br>';
}
}
</script>
</body>
</html>
Common Use Cases
The finally block is commonly used for:
- Resource cleanup: Closing files, database connections, or network connections
- Logging: Recording that an operation completed, regardless of success or failure
- UI updates: Hiding loading spinners or re-enabling buttons
- State reset: Restoring application state after an operation
Key Points
| Scenario | Try Block | Catch Block | Finally Block |
|---|---|---|---|
| No Error | ? Executes | ? Skipped | ? Always executes |
| Error Occurs | ? Stops at error | ? Executes | ? Always executes |
Conclusion
The finally block guarantees code execution after try/catch blocks, making it essential for cleanup operations and ensuring critical code always runs regardless of errors.
Advertisements
