JavaScript is a powerful language, but like any programming language, it encounters errors. Proper exception handling ensures smooth execution and helps debug issues effectively. In this blog, we will explore different ways to handle exceptions in JavaScript with examples.
JavaScript errors can be classified into three main types:
Syntax Errors – Occur when there is an issue in the code syntax.
Runtime Errors – Occur during execution, such as calling an undefined function.
Logical Errors – Happen due to incorrect logic but do not throw explicit errors.
try...catch
StatementThe try...catch
statement is the most common way to handle exceptions in JavaScript.
try {
// Code that may throw an error
} catch (error) {
// Handle the error
} finally {
// Code that runs regardless of an error
}
try {
let result = 10 / 0; // Division by zero (infinity, not an error in JS)
console.log(result);
let x = y; // ReferenceError: y is not defined
} catch (error) {
console.error("An error occurred:", error.message);
} finally {
console.log("Execution completed.");
}
You can create and throw custom errors using the throw
statement.
function validateAge(age) {
if (age < 18) {
throw new Error("Age must be 18 or above.");
}
return "Access granted";
}
try {
console.log(validateAge(16));
} catch (error) {
console.error("Validation Error:", error.message);
}
finally
The finally
block always executes, whether an exception occurs or not.
try {
console.log("Trying to execute code...");
throw new Error("An unexpected error");
} catch (error) {
console.error("Caught an error:", error.message);
} finally {
console.log("This will always execute.");
}
Use try...catch
for handling predictable errors.
Avoid catching and ignoring errors without logging them.
Use meaningful error messages for debugging.
Prefer specific error handling instead of catching all exceptions.
Always clean up resources in the finally
block if needed.
Exception handling in JavaScript is crucial for writing robust and error-free applications. By using try...catch
, finally
, and custom error handling techniques, you can improve the stability of your code. Implement these practices in your JavaScript projects to handle errors efficiently.