JavaScript Error Handling – try, catch, finally, and throw
In JavaScript, error handling is essential to ensure your code runs smoothly, even when unexpected things happen. The keywords try, catch, finally, and throw allow you to manage errors gracefully.
1. try...catch – Catch Runtime Errors
Example:
try {
let result = 10 / 0;
console.log("Result:", result);
} catch (error) {
console.log("An error occurred:", error.message);
}
Output
Result: Infinity
No error here, but if something goes wrong in the try block, the catch block will handle it.
Example with Actual Error:
try {
undefinedFunction(); // this function doesn't exist
} catch (error) {
console.log("Error caught:", error.message);
}
Output
Error caught: undefinedFunction is not defined
Use When: You want to prevent your app from crashing due to unexpected errors.
2. throw – Create Custom Errors
You can create and throw your own errors using throw.
Example:
function divide(a, b) {
if (b === 0) {
throw new Error("Cannot divide by zero!");
}
return a / b;
}
try {
console.log(divide(10, 0));
} catch (e) {
console.log("Caught Error:", e.message);
}
Output
Caught Error: Cannot divide by zero!
Use When: You want to trigger a custom error based on a condition.
3. finally – Always Executes
The finally block runs no matter what — even if there's an error.
Example:
try {
console.log("Trying something...");
// some code that may throw
} catch (err) {
console.log("Caught an error!");
} finally {
console.log("This always runs.");
}
Output
Trying something...
This always runs.
This always runs.
Use When: You need cleanup actions like closing a connection, logging, or hiding a loader.
Real-World Use Case: Form Validation
function validateForm(name) {
if (name === "") {
throw new Error("Name field is required.");
}
return "Form submitted!";
}
try {
console.log(validateForm(""));
} catch (e) {
console.log("Validation Error:", e.message);
} finally {
console.log("Form check complete.");
}
Output
Validation Error: Name field is required.
Form check complete.
Form check complete.