try...catch
- This lesson explains how to use try...catch for handling exceptions.
Introduction to Error Handling
In real-world JavaScript applications, errors are unavoidable.
Errors can occur due to:Invalid user input
Network issues
Logical mistakes
Missing data
Unexpected runtime behavior
If errors are not handled properly:
Program may crash
Application may stop working
User experience becomes poor
Error handling allows us to:
Detect errors
Prevent application crashes
Display meaningful messages
Debug issues easily
What Is an Error in JavaScript ?
An error is a problem that occurs during the execution of a program and stops normal execution.
Example of an error:
console.log(x);
If x is not defined, JavaScript throws an error.
Types of Errors in JavaScript (Brief)
Syntax Error – Mistake in code structure
Reference Error – Variable not defined
Type Error – Wrong data type operation
Range Error – Value out of range
In this lesson, we focus on handling runtime errors.
try...catch
What Is try...catch ?
The try...catch statement is used to handle runtime errors safely.
It allows JavaScript to:
Try executing risky code
Catch errors if they occur
Continue program execution
Basic Syntax of try...catch
try {
// code that may cause an error
} catch (error) {
// code to handle the error
}
How try...catch Works
Code inside try block executes
If no error occurs → catch is skipped
If error occurs → control moves to catch
Program does not crash
Runtime Error Handling Example
Uses try-catch to handle unexpected errors during execution.
try {
let result = 10 / x;
console.log(result);
} catch (error) {
console.log("An error occurred");
}
If x is not defined, the error is caught.
Accessing Error Details
The catch block receives an error object.
Reference Error Handling Example
Catches and displays error when using an undefined variable.
try {
console.log(y);
} catch (error) {
console.log(error.message);
}
Custom Error Handling Example
Validates input and throws a custom error for invalid conditions.
function divide(a, b) {
try {
if (b === 0) {
throw new Error("Division by zero is not allowed");
}
return a / b;
} catch (error) {
return error.message;
}
}
console.log(divide(10, 0));
Important Rules of try...catch
Works only for runtime errors
Does not catch syntax errors
try block must be followed by catch or finally
Custom Errors
What Are Custom Errors ?
Custom errors are user-defined errors created to handle specific situations.
They help:
Make error messages meaningful
Improve debugging
Control application flow
Creating Custom Errors Using throw
JavaScript provides the throw keyword to create errors.
Syntax
throw new Error("Error message");
Custom Validation Error Example
Throws and handles an error when input does not meet conditions.
function checkAge(age) {
if (age < 18) {
throw new Error("Age must be 18 or above");
}
return "Access granted";
}
try {
console.log(checkAge(16));
} catch (error) {
console.log(error.message);
}
Throwing Different Types of Errors
throw new TypeError("Invalid type");
throw new RangeError("Value out of range");
Why Use Custom Errors ?
Clear error identification
Better control over program logic
User-friendly error messages
Easier maintenance
finally Block
What Is the finally Block ?
The finally block contains code that always executes, regardless of whether:
An error occurred
An error was caught
No error occurred
Syntax with finally
try {
// risky code
} catch (error) {
// error handling
} finally {
// always runs
}
Try-Catch-Finally Example
Demonstrates execution of try, catch, and finally blocks.
try {
console.log("Try block");
throw new Error("Something went wrong");
} catch (error) {
console.log("Catch block");
} finally {
console.log("Finally block");
}
When to Use finally
Closing database connections
Clearing timers
Releasing resources
Cleanup operations
Finally Cleanup Example
Uses finally block to execute code after try-catch.
try {
console.log("Processing data");
} catch (error) {
console.log("Error occurred");
} finally {
console.log("Process completed");
}
Flow Control Summary
Common Mistakes
Using try...catch for simple logic
Catching errors without handling them
Writing vague error messages
Forgetting finally for cleanup
Overusing throw
Best Practices for Error Handling
Handle only necessary code inside try
Write clear and meaningful error messages
Use custom errors for validations
Avoid empty catch blocks
Always clean up resources in finally
Real-World Applications of Error Handling
Form validation
API response handling
Payment processing
File handling
Authentication systems