try...catch statement is used to handle exceptions in JavaScript. It tests a block of code for errors and catches those errors without stopping the execution of the program.
try { let result = 10 / 0; // This will not throw an error, but results in Infinity console.log(result); } catch (error) { console.log("An error occurred: " + error.message); }
Explanation: The try block contains code that might cause an error. If no error occurs, the catch block is skipped. If an error happens, the catch block is executed.
Output:
try { let a = undefinedVariable; // This will throw a ReferenceError } catch (error) { console.log("An error occurred: " + error.message); }
Explanation: This time, the code inside the try block tries to access a variable that hasn't been defined, causing a ReferenceError.
Output:
Throwing your own errors in JavaScript using the throw
statement can be useful for custom error handling.
function checkAge(age) { if (age < 18) { throw new Error("Age must be 18 or older"); } else { console.log("Age is valid"); } } try { checkAge(15); // This will throw an error } catch (error) { console.log("Error: " + error.message); }
Explanation: The checkAge function throws an error if the age is less than 18. The try...catch block catches the error and prints the custom error message.
Output:
JavaScript error objects contain useful information such as name
, message
, and stack
.
try { let num = 10; let result = num / 0; // This results in Infinity, which is not an error, but let's simulate a custom error if (result === Infinity) { throw new Error("Division by zero is not allowed"); } } catch (error) { console.log("Error Name: " + error.name); console.log("Error Message: " + error.message); console.log("Error Stack: " + error.stack); }
Explanation: The error is thrown manually when we detect an "infinity" result from a division by zero. The error object contains the name of the error, the message, and the stack trace.
Output:
Debugging is the process of identifying and fixing errors in your code. Here are a few common techniques:
The console.log()
method is one of the most common debugging techniques to inspect values and flow in your code.
function addNumbers(a, b) { console.log("Inputs:", a, b); // Debugging the inputs return a + b; } addNumbers(3, 5);
Output:
This is used to print errors to the console. It's helpful when you want to separate error messages from general logs.
function calculateAge(yearOfBirth) { if (yearOfBirth > 2023) { console.error("Error: Year of birth cannot be in the future."); return; } return 2023 - yearOfBirth; } calculateAge(2025);
Output:
The debugger
statement is used to pause the execution of JavaScript and start debugging. When the code reaches the debugger
statement, the JavaScript engine stops and opens the debugger (if available in the browser).
function findSquare(num) { debugger; // Pauses the execution here return num * num; } findSquare(5);
Explanation: The debugger
statement causes the execution to stop, allowing you to inspect the current state of the application.
If you suspect a particular block of code might throw an error, wrap it in a try...catch
block to capture the error and inspect its properties.
try { let number = "5"; let result = number * 2; // Implicit type coercion might be causing issues console.log(result); } catch (error) { console.log("Caught an error:", error); }
Output:
try { let a = 10; let b = 0; if (b === 0) { throw new Error("Cannot divide by zero"); } let result = a / b; console.log(result); } catch (error) { console.log("Error caught:", error.message); }
Output: