In JavaScript, try-catch statements are used to handle errors that occur during the execution of a program. A try…catch block consists of two main parts:
tryblock: This is the block of code that may throw an error. If an error is thrown, the execution of thetryblock is immediately stopped, and control is passed to the nearestcatchblock.catchblock: This is the block of code that is executed when an error is caught. It takes an argument that represents the error object, which can be used to retrieve information about the error. Thecatchblock should contain code that handles the error and gracefully handles the failure.
The syntax of a try...catch statement in JavaScript is as follows:
try {
// Code that may throw an error
} catch (error) {
// Code to handle the error
}This approach can help you handle errors in a more controlled and predictable way.
JavaScript try-catch example
A simple example code will throw a ReferenceError.
<!DOCTYPE html>
<html>
<body>
<script>
try {
let x = y + 1;
} catch (error) {
console.log(`Error: ${error.message}`);
}
</script>
</body>
</html>Output:

Catching a TypeError
try {
let x = null;
x.toUpperCase(); // This will throw a TypeError
} catch (error) {
console.log(`Error: ${error.message}`);
}Another example
function divide(num1, num2) {
try {
if (num2 === 0) {
throw new Error("Cannot divide by zero");
}
return num1 / num2;
} catch (error) {
console.log(`Error: ${error.message}`);
return null;
}
}
console.log(divide(10, 0)); // Output: Error: Cannot divide by zero, null
console.log(divide(10, 2)); // Output: 5
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