Error Handling in JavaScript: Try, Catch, Finally
What Are Errors in JavaScript?
Errors occur when something goes wrong during code execution.
Examples:
Invalid variable
Wrong input
Failed API request
File not found
Runtime Error Example
console.log(userName);
Output
ReferenceError: userName is not defined
The program crashes because the variable does not exist.
Why Error Handling Matters
Error handling helps applications:
Fail gracefully
Prevent crashes
Show meaningful messages
Improve debugging
What Is try...catch?
try contains risky code.
catch handles errors if they occur.
Basic Syntax
try {
// risky code
} catch (error) {
// handle error
}
Example
try {
console.log(userName);
} catch (error) {
console.log("Something went wrong");
}
Output
Something went wrong
Instead of crashing, the error is handled safely.
Error Handling Flow
Accessing Error Information
try {
console.log(userName);
} catch (error) {
console.log(error.message);
}
Output
userName is not defined
The finally Block
finally always runs:
Whether error happens or not
After try and catch
Syntax
try {
// code
} catch (error) {
// handle error
} finally {
// always runs
}
Example
try {
console.log("Running code");
} catch (error) {
console.log("Error occurred");
} finally {
console.log("Cleanup completed");
}
Output
Running code Cleanup completed
Example With Error
try {
console.log(userName);
} catch (error) {
console.log("Handled error");
} finally {
console.log("Finally always runs");
}
Output
Handled error Finally always runs
Try → Catch → Finally Flow
Throwing Custom Errors
You can manually create 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 (error) {
console.log(error.message);
}
Output
Cannot divide by zero
Why Throw Custom Errors?
Custom errors help:
Validate input
Stop invalid operations
Provide meaningful messages
Real-World Example
function login(password) {
if (!password) {
throw new Error("Password is required");
}
console.log("Login successful");
}
Common Error Types
Example: TypeError
const number = 10; number.toUpperCase();
Output
TypeError
Numbers do not have toUpperCase().
Graceful Failure
Without error handling:
Application crashes
With error handling:
Application continues safely
Common Beginner Mistake
Incorrect:
try {
console.log(userName);
}
Missing catch or finally.
Practical Example
try {
const data = JSON.parse("{ invalid json }");
console.log(data);
} catch (error) {
console.log("Invalid JSON format");
}
Key Takeaways
Final Notes
Error handling is critical in real-world applications because failures always happen:
Invalid user input
Network issues
Database failures
API errors
Good error handling makes applications:
Stable
Easier to debug
More user-friendly
0 Comments
Sign in to join the conversation
No comments yet. Be the first to comment!