- Array() find
- -- operator
- -= operator
- ++ operator
- += operator
- Accessing and setting content
- AND operator
- Array concat() method
- Array indexOf()
- Array length
- Array pop()
- Array shift
- Array slice() method
- Arrays
- Async await
- Booleans
- Braces
- Callback function
- Calling the function
- Class
- Closure
- Code block
- Comment
- Conditions
- Console
- Constructor
- Creating a p element
- Data types
- Date getTime()
- Destructuring
- Else
- Else if
- Enum
- Environment
- Equals operator
- Error Handling
- ES6
- Event loop
- Events
- Extends
- Fetch API
- Filter
- For loop
- forEach()
- Function
- Function bind()
- Function name
- Greater than
- Head element
- Hoisting
- If statement
- includes()
- Infinity property
- isNaN function
- Iterator
- JSON
- Less than
- Local storage
- Map
- Methods
- Module
- Modulo operator
- null
- Numbers
- Object
- Object.keys()
- Overriding methods
- Parameters
- Promises
- Prototype
- Random
- Reduce
- Regex
- Regular expressions
- Removing an element
- Replace
- Scope
- Session storage
- setTimeout() method
- Sleep() function
- Sort
- Splice
- String
- String concat()
- String indexOf()
- String slice() method
- Substring
- Switch statement
- Template literals
- Ternary operator
- throw Statement
- Title
- Try catch
- Type conversion
- undefined
- void Operator
- What is JavaScript?
- While loop
JAVASCRIPT
JavaScript try catch: Syntax, Usage, and Examples
JavaScript try...catch lets you run risky code without taking down your whole app. You wrap the fragile part in a block, catch any thrown error, and respond in a controlled way.
How to Use try...catch in JavaScript
At its core, the JavaScript try catch structure looks like this:
Learn JavaScript on Mimo
try {
// Code that might throw an error
} catch (error) {
// Code that runs if an error happens
}
try: Wraps the code that might fail.catch (error): Runs only if something intrythrows. Theerrorparameter holds the thrown value (often anErrorobject).
Any time code inside the try block throws, execution jumps straight into the catch block.
A slightly more complete pattern also includes finally:
try {
// risky work
} catch (error) {
// handle or log the error
} finally {
// cleanup code that always runs
}
The finally block always runs, no matter if the try succeeded or the catch handled an exception.
You don’t usually throw arbitrary strings. A more helpful pattern throws proper Error objects:
function parseConfig(text) {
try {
const data = JSON.parse(text);
return data;
} catch (error) {
throw new Error("Invalid configuration file");
}
}
In this example, the JavaScript try catch block converts low-level JSON errors into a clear, higher-level “invalid configuration” error for the rest of the app.
When to Use JavaScript try catch
You don’t need a try catch JavaScript block around every second line of code. That would just hide bugs. Instead, use try...catch where failure is likely, expected, and recoverable.
Here are common scenarios.
1. Dealing With Unreliable Input
Any time your code parses user input, uploaded files, or data from unknown sources, things can go sideways. A simple typo in JSON can break parsing.
A JavaScript try catch block around parsing keeps your app from crashing and lets you show a friendly message instead of a stack trace.
2. Working With External Systems
Network requests, file APIs, localStorage, and other browser features depend on permissions, network stability, and device quirks. They can throw exceptions when something goes wrong.
Using try catch in JavaScript around these calls lets you:
- Retry when a temporary problem appears
- Fall back to another option
- Log the error for later investigation
3. Isolating Risky Features
Sometimes, only one small part of a feature is fragile. For example, a single widget on a dashboard that relies on a third-party script.
Wrapping just that widget withtry catch keeps one broken card from killing the entire page. The rest of the UI can keep working while you show a small “Sorry, this panel failed to load” message.
4. Making Errors Understandable
The raw text of an exception can be cryptic for non-technical users. A try catch exception JavaScript pattern lets you translate low-level errors into clear language and save the technical details to logs.
For example, instead of “TypeError: Cannot read properties of undefined,” your app can show “That playlist could not be loaded, please try again.”
5. Handling Async Code With async/await
Modern JavaScript often uses async/await. Any await inside try can throw if the underlying promise rejects. A try catch JavaScript block around the await calls lets you handle problems just like synchronous exceptions.
Examples of try...catch in JavaScript
Let’s look at concrete patterns you’ll actually use, not just bare syntax.
Example 1: Parsing JSON Safely
Users paste JSON into a settings screen. One stray comma breaks everything unless you handle it.
function loadSettings(jsonText) {
try {
const settings = JSON.parse(jsonText);
console.log("Settings loaded:", settings);
return settings;
} catch (error) {
console.error("Could not parse settings:", error.message);
return null; // signal failure
}
}
const input = '{ "theme": "dark", "fontSize": 16 }';
const settings = loadSettings(input);
if (!settings) {
// show message, keep using default settings
}
Here, the try catch block keeps the rest of the app alive and lets you fall back to defaults.
Example 2: Handling localStorage Failures
Some users disable storage, browse in privacy modes, or hit quota limits. That’s a good place for try catch.
function saveTheme(theme) {
try {
localStorage.setItem("theme", theme);
} catch (error) {
console.warn("Could not save theme preference:", error.message);
}
}
saveTheme("dark");
Even if an error happens, the page still works. You just lose the preference, which is acceptable in many apps.
Example 3: Using try...catch With async/await
A very common pattern is combining await and JavaScript try catch when calling APIs.
async function fetchProfile(userId) {
try {
const response = await fetch(`/api/profile/${userId}`);
if (!response.ok) {
throw new Error(`Server returned ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error("Failed to load profile:", error);
return null;
}
}
(async () => {
const profile = await fetchProfile(42);
if (!profile) {
console.log("Showing fallback profile UI.");
}
})();
Here you see a classic try catch exception pattern: detect network or server issues, log them, and return null so the caller can show a fallback state.
Example 4: Validating and Rethrowing Errors
Sometimes you want to catch only specific problems and rethrow others so they bubble up.
function readAge(value) {
try {
const age = Number(value);
if (Number.isNaN(age)) {
throw new Error("Age must be a number");
}
if (age < 0) {
throw new Error("Age cannot be negative");
}
return age;
} catch (error) {
// add context, then rethrow
throw new Error(`Invalid age input: ${error.message}`);
}
}
Thetry catch block here focuses on input validation but still lets the broader error bubble up to a higher-level handler.
Example 5: Cleanup With finally
Imagine a loading spinner in a UI. You want to hide whether the operation succeeded or failed.
async function loadDashboard() {
showSpinner();
try {
const data = await fetch("/api/dashboard").then(r => r.json());
renderDashboard(data);
} catch (error) {
console.error("Dashboard load failed:", error);
showErrorMessage("Could not load dashboard.");
} finally {
hideSpinner();
}
}
The finally block hides the spinner in all cases, which keeps the UI consistent.
Learn More About JavaScript try catch
Once you’re comfortable with the basics, a few extra details make your error handling much more effective.
The Error Object in catch
The value caught by catch is often an instance of Error:
try {
throw new Error("Something went wrong");
} catch (error) {
console.log(error.name); // "Error"
console.log(error.message); // "Something went wrong"
console.log(error.stack); // stack trace (useful for debugging)
}
Many “try catch” examples skip the name and stack properties, but they’re great for logging. Adding those details to error reports helps you debug production issues.
Throwing Custom Errors
You’re not limited to basic Error. You can create custom subclasses:
class ValidationError extends Error {
constructor(message, field) {
super(message);
this.name = "ValidationError";
this.field = field;
}
}
function validateEmail(email) {
if (!email.includes("@")) {
throw new ValidationError("Invalid email address", "email");
}
}
A higher-level handler can use try catch blocks to detect ValidationError specifically and show precise messages next to form fields.
Nested try...catch and Rethrowing
You can also nest try catch when different layers need separate handling, though you should use nesting sparingly for readability.
function processOrder(order) {
try {
chargeCard(order);
} catch (error) {
logPaymentError(error);
throw error; // let caller decide what UI to show
}
}
try {
processOrder(currentOrder);
showSuccessMessage();
} catch {
showErrorMessage("Payment failed. Please try again.");
}
The inner try catch focuses on logging, while the outer one focuses on user experience.
What try...catch Does Not Catch
Important limitation: a try catch block only catches errors thrown synchronously in its body, or from awaited promises.
This means:
- Errors in
setTimeoutcallbacks won’t be caught by a surrounding synchronoustry...catch. - Promise rejections need either
.catch()or anawaitinsidetry.
For example, this does not work:
try {
setTimeout(() => {
throw new Error("Async error"); // not caught by outer try...catch
}, 0);
} catch (error) {
console.log("Will never run");
}
To handle these, you put a separate try catch in the callback, or you restructure code to use async/await.
Balancing Validation and Exceptions
A good rule of thumb: use regular checks for expected situations and try catch exception patterns for truly exceptional ones.
For example, checking if a form field is empty is an everyday case. A simple if (!email) is enough. Reserve exceptions for cases that indicate programming errors, failed network calls, or other unexpected situations.
Too much try catch can hide bugs, while too little can crash your app for small issues. Over time, you’ll develop a sense for where the balance feels right.
Summary
try catch gives you a safety net around fragile sections of code. You wrap risky logic in try, handle errors in catch, and use finally for cleanup that always runs. That pattern works for parsing JSON, talking to APIs, managing storage, and handling async code with await.
As you write more real projects, you’ll see try catch everywhere: around network calls, in form validation helpers, and inside state management logic.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.