JavaScript Try Catch Explained for Beginners (Examples)
Learn how JavaScript try catch works with simple examples. Handle errors, use finally and throw, and stop your code from crashing. Beginner friendly.
Learn how JavaScript try catch works with simple examples. Handle errors, use finally and throw, and stop your code from crashing. Beginner friendly.
Want to know how try catch works in JavaScript? Here is the short answer: try catch lets you run code that might fail, and then handle the problem yourself instead of letting your program crash. You put risky code inside try. If an error happens, JavaScript jumps to catch, where you decide what to do next.
This guide explains JavaScript try catch for beginners. We will go slowly, define every new word, and use small examples you can paste into your browser console or a .js file.
An error is a message that tells you something went wrong while your code was running. For example, you might use a variable that does not exist, or read data that is broken. When this happens and nothing handles it, JavaScript stops running the rest of your code. This is often called a crash.
console.log('Start');
console.log(userName);
console.log('End');Line 1 prints Start. Line 2 tries to print a variable called userName, but we never created it, so JavaScript throws a ReferenceError. Line 3 never runs, so End is never printed. Try catch fixes this kind of problem.
Syntax means the exact way you must write code so JavaScript understands it. Here is the pattern:
try {
console.log(userName);
} catch (error) {
console.log('Something went wrong');
}
console.log('End');The try block holds the code we want to attempt. If it fails, JavaScript skips the rest of the try block and runs the catch block. The word error inside the parentheses is a variable that holds details about the problem. The last line runs normally, so End is printed. Your program did not crash.
The error variable is an object (a bundle of named values). Two useful parts are name, the type of error, and message, a sentence describing it.
try {
console.log(userName);
} catch (error) {
console.log(error.name);
console.log(error.message);
}The first log prints ReferenceError. The second prints userName is not defined. Reading these two values is the fastest way to understand what went wrong.
| Error type | What it means | Example |
|---|---|---|
| ReferenceError | You used a variable that does not exist | console.log(missing) |
| TypeError | You used a value in the wrong way | null.length |
| SyntaxError | The code is written incorrectly | JSON.parse('{bad') |
| RangeError | A number is outside the allowed range | new Array(-1) |
You do not need to memorize these. Just know that the name tells you the category of the problem.
You can add a third block called finally. It runs every time, whether an error happened or not. People use it for clean-up work, such as hiding a loading message.
try {
console.log('Trying...');
JSON.parse('not json');
} catch (error) {
console.log('Failed:', error.message);
} finally {
console.log('Done');
}Trying... prints first. JSON.parse fails because the text is not valid JSON, so catch prints the failure message. Then finally prints Done. If the parse had worked, Done would still print.
JSON is a text format for sharing data. JSON.parse turns JSON text into a JavaScript object, but it throws an error when the text is broken. This is a perfect use for try catch.
function readUser(text) {
try {
return JSON.parse(text);
} catch (error) {
return null;
}
}
console.log(readUser('{"name":"Sam"}'));
console.log(readUser('oops'));The function readUser takes some text. It tries to parse it and return the result. If parsing fails, it returns null, which means no value. The first call prints an object with the name Sam. The second prints null instead of crashing.
You can create an error yourself with the throw keyword. This is useful when a value is not acceptable for your program.
function divide(a, b) {
if (b === 0) {
throw new Error('You cannot divide by zero');
}
return a / b;
}
try {
console.log(divide(10, 2));
console.log(divide(5, 0));
} catch (error) {
console.log(error.message);
}Inside divide, we check whether b is zero. If so, we throw a new Error with our own message. In the try block, the first call prints 5. The second call throws, so JavaScript jumps to catch and prints our message.
When you fetch data from the internet using async/await, things can fail, for example if the network is down. Wrap the await lines in try catch.
async function loadPost() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
const post = await response.json();
console.log(post.title);
} catch (error) {
console.log('Could not load the post');
}
}
loadPost();The function is marked async so we can use await inside. Each await waits for a result. If any step fails, catch runs and prints a friendly message. Note that fetch does not throw for a 404 page, so for full checks you can also look at response.ok.
New to async code? Read our guide to async/await first, then come back and add try catch to your own requests.
Read the async/await guideIt runs code that might fail and lets you handle any error instead of crashing. The try block holds the risky code. The catch block runs only if an error is thrown.
The catch block runs only when an error happens. The finally block runs every time, with or without an error. Use finally for clean-up steps.
No. Use it around code that can really fail, such as parsing JSON, reading user input, or network requests. Too many try catch blocks make code harder to read.
Yes. Put your await calls inside a try block and handle failures in catch. This is the standard way to handle errors in async functions.
Use the throw keyword with an Error object, like throw new Error('Message'). JavaScript stops the current code and jumps to the nearest catch block.
You now know how to use try, catch, finally, and throw. Practice by breaking small pieces of code on purpose and handling the errors. That is the best way to feel confident.
Want help turning what you learn into a real website or app? Our team is happy to chat.
Talk to FepiqOccasional, no-fluff notes on shipping modern software — startups, automation, Laravel, Shopify and more. No spam, unsubscribe anytime.
Keep reading
Learn SQL CASE WHEN step by step. This beginner guide shows how to label, group and sort data with simple examples you can copy and run today.
PostgreSQL ILIKE explained for beginners: search text without worrying about case, learn % and _ wildcards, and copy simple examples you can run today.
Let's build something
Book a free discovery call. We'll listen, ask sharp questions, and send you a proposal within 3 business days.