In JavaScript, the try catch finally statement is used to handle errors and perform cleanup operations regardless of whether an error occurs or not.
The try
block contains the code that may throw an error, and the catch
block contains code to handle the error. The finally
block contains code that will always execute, regardless of whether an error was thrown or caught.
The basic syntax of try-catch-finally
is:
try {
// Code that may throw an error
} catch (error) {
// Code to handle the error
} finally {
// Code that will always execute
}
Here’s how the try-catch-finally
works:
- The
try
block contains the code that may throw an error. - If an error is thrown in the
try
block, control is transferred to thecatch
block. - The
catch
block contains code to handle the error. It takes an argument (usually namederror
) that contains information about the error that was thrown. - If an error is not thrown in the
try
block, thecatch
block is skipped. - The
finally
block contains code that will always execute, regardless of whether an error was thrown or caught. This block is optional. - If there is no
catch
block, the error will be thrown to the next higher level of code.
JavaScript try catch finally examples
Simple example code.
<!DOCTYPE html>
<html>
<body>
<script>
function divide(a, b) {
try {
if (b === 0) {
throw new Error("Division by zero is not allowed.");
}
return a / b;
} catch (error) {
console.log(error.message);
} finally {
console.log("Division operation complete.");
}
}
console.log(divide(10, 2));
console.log(divide(10, 0));
</script>
</body>
</html>
Output:
Parsing JSON
const jsonString = '{ "name": "John", "age": 30 }';
try {
const obj = JSON.parse(jsonString);
console.log(obj.name);
} catch (error) {
console.log(`Error parsing JSON: ${error.message}`);
} finally {
console.log('JSON parse operation complete.');
}
Closing a database connection
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'mydb'
});
try {
connection.connect();
console.log('Connected to database.');
// Code that interacts with the database goes here
} catch (error) {
console.log(`Error connecting to database: ${error.message}`);
} finally {
connection.end();
console.log('Database connection closed.');
}
Network Requests
const fetch = require('node-fetch');
async function fetchUserData(userId) {
try {
const response = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`);
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
const data = await response.json();
console.log(data);
} catch (error) {
console.log(`Error fetching user data: ${error.message}`);
} finally {
console.log('User data fetch operation complete.');
}
}
fetchUserData(1);
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