Exception handling in JavaScript is used to manage runtime errors without stopping the entire program. It helps developers write stable and reliable applications.
What is an Exception?
An exception is an unexpected error that occurs while the program is running.
Examples:
- Dividing by invalid values
- Accessing undefined variables
- Invalid JSON parsing
- Network/API failures
- Custom validation errors
Why Exception Handling is Important
Exception handling helps to:
- Prevent application crashes
- Show meaningful error messages
- Debug applications easily
- Handle API/database failures gracefully
- Improve user experience
JavaScript Error Types
1. Syntax Error
Occurs when JavaScript code has invalid syntax.
console.log("Hello"
Output:
SyntaxError: missing ) after argument list
2. Reference Error
Occurs when accessing an undefined variable.
console.log(userName);
Output:
ReferenceError: userName is not defined
3. Type Error
Occurs when an operation is performed on the wrong data type.
let num = 10;
num.toUpperCase();
Output:
TypeError: num.toUpperCase is not a function
4. Range Error
Occurs when a value is outside the allowed range.
let arr = new Array(-1);
Output:
RangeError: Invalid array length
5. URI Error
Occurs when URI functions are used incorrectly.
decodeURIComponent("%");
Output:
URIError: URI malformed
try…catch Statement
The try...catch block is the core of exception handling.
Syntax
try {
// risky code
} catch(error) {
// error handling code
}
Basic Example
try {
let result = 10 / 0;
console.log(result);
} catch(error) {
console.log("Something went wrong");
}
Example with Actual Error
try {
console.log(user);
} catch(error) {
console.log("Error Name:", error.name);
console.log("Error Message:", error.message);
}
Output:
Error Name: ReferenceError
Error Message: user is not defined
Error Object Properties
The error object contains useful information.
| Property | Description |
|---|---|
name | Error type |
message | Error description |
stack | Stack trace |
finally Block
The finally block always executes whether an error occurs or not.
Syntax
try {
// code
} catch(error) {
// handle error
} finally {
// always runs
}
Example
try {
console.log("Start");
console.log(data);
} catch(error) {
console.log("Error handled");
} finally {
console.log("Execution completed");
}
Output:
Start
Error handled
Execution completed
throw Statement
The throw keyword is used to create custom exceptions.
Syntax
throw "Custom Error";
or
throw new Error("Invalid input");
Custom Error Example
let age = 15;
try {
if(age < 18) {
throw new Error("Age must be 18 or above");
}
console.log("Eligible");
} catch(error) {
console.log(error.message);
}
Output:
Age must be 18 or above
Nested try…catch
You can use multiple try-catch blocks.
try {
try {
console.log(userName);
} catch(error) {
console.log("Inner Catch");
}
console.log(data);
} catch(error) {
console.log("Outer Catch");
}
Exception Handling in Functions
function divide(a, b) {
try {
if(b === 0) {
throw new Error("Division by zero not allowed");
}
return a / b;
} catch(error) {
return error.message;
}
}
console.log(divide(10, 0));
Exception Handling with JSON
Very common in API automation and backend development.
let jsonData = '{"name":"Deepesh"}';
try {
let user = JSON.parse(jsonData);
console.log(user.name);
} catch(error) {
console.log("Invalid JSON");
}
Invalid JSON Example
let jsonData = '{"name":"Deepesh"';
try {
let user = JSON.parse(jsonData);
} catch(error) {
console.log("JSON Parsing Failed");
}
Async Exception Handling
Used with async/await.
Example
async function fetchData() {
try {
let response = await fetch("https://dummyjson.com/users/1");
let data = await response.json();
console.log(data);
} catch(error) {
console.log("API Error:", error.message);
}
}
fetchData();
Best Practices
1. Use Specific Error Messages
throw new Error("Password cannot be empty");
2. Avoid Empty catch Blocks
❌ Bad
catch(error) {
}
✅ Good
catch(error) {
console.log(error.message);
}
3. Use finally for Cleanup
Useful for:
- Closing database connections
- Clearing resources
- Stopping loaders
4. Do Not Overuse try…catch
Use it only around risky code.
Real-World Example
Form Validation
function login(username, password) {
try {
if(!username) {
throw new Error("Username is required");
}
if(!password) {
throw new Error("Password is required");
}
console.log("Login Successful");
} catch(error) {
console.log(error.message);
}
}
login("", "12345");