Javascript try catch
Created By: chatGPT
try...catch
is a powerful feature in JavaScript that allows you to handle exceptions gracefully. It enables the programmer to test a block of code for errors while allowing the program to continue running even if an error occurs. Here’s how you can use it:try {
// Code that may throw an error
let result = riskyFunction();
console.log(result);
} catch (error) {
// Code that runs if an error occurs
console.error('An error occurred:', error.message);
}
The
try
block contains the code that you want to execute. If an error occurs within this block, the flow of control is passed to the catch
block. The error
object contains information about the error that occurred, which you can use to perform error handling.function riskyFunction() {
throw new Error('This is a test error!');
}
try {
riskyFunction();
} catch (error) {
console.error('Caught an error:', error.message);
}
You can also use an optional
finally
block that will run regardless of whether an error occurred or not. This is useful for cleaning up resources or executing code that must run after try
and catch
.try {
// Code that may throw an error
let z = 10;
console.log(z / 0); // This will not throw an error but output Infinity
} catch (error) {
console.error('Caught an error:', error.message);
} finally {
console.log('This always executes.');
}
Using
try...catch
is essential for building robust applications. It prevents your application from crashing due to unhandled errors and provides a way to manage those errors effectively.function calculateDivision(a, b) {
try {
if (b === 0) throw new Error('Division by zero');
return a / b;
} catch (error) {
console.error(error.message);
return null; // Return a default value or handle exception
}
}
let result = calculateDivision(10, 0); // Caught an error: Division by zero