In JavaScript, you can use a try-finally block without a catch block. The try
block contains the code used to execute and the finally block contains the code you want to execute regardless of whether an exception is thrown.
try {
// Code to try
} finally {
// Code to always execute
}
If an exception is thrown in the try
block, the finally
block will still be executed.
This can be useful for cleaning up resources, such as closing files or database connections, regardless of whether an exception was thrown or not.
JavaScript try-finally without catch example
Simple example code handles a division by zero error in JavaScript:
<!DOCTYPE html>
<html>
<head>
<script>
function divide(a, b) {
let result = null;
try {
result = a / b; // Divide a by b
return result;
} catch (error) {
console.log("Error: " + error.message);
return null;
} finally {
console.log("Division attempted");
}
}
console.log(divide(10, 0));
console.log(divide(10, 5));
</script>
</head>
<body>
<!-- Your HTML code here -->
</body>
</html>
Output:
In the first call to divide
, the division by zero results in a TypeError
exception being thrown. The catch
block catches the exception, logs an error message to the console, and returns null. The finally
block still executes and logs a message indicating that the division was attempted.
More examples
function openFileAndReadContent(filename) {
let file = null;
try {
file = openFile(filename); // Open the file
const content = readFile(file); // Read the file
return content; // Return the file content
} finally {
if (file !== null) {
closeFile(file); // Close the file if it was opened
}
}
}
function connectToDatabase() {
let connection = null;
try {
connection = createConnection(); // Create a database connection
// Execute some database queries
console.log("Connected to database!");
} finally {
if (connection !== null) {
closeConnection(connection); // Close the database connection if it was created
}
}
}
function fetchDataFromApi(apiUrl) {
let response = null;
try {
response = makeApiRequest(apiUrl); // Make an API request
const data = extractDataFromResponse(response); // Extract the data from the response
return data; // Return the data
} finally {
if (response !== null) {
closeApiResponse(response); // Close the API response if it was received
}
}
}
Comment if you have any doubts or suggestions on this JS exception handling the topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version