🇬🇧 Limited Time — UK Only·🎓 Free Learning for 1 Month·🤖 Free AI Training Included·📚 4,000+ Lessons · 35,000+ Quizzes·🏆 GCSE Mocks · Olympiad Papers·⚡ Selected Students Only · Limited Places·🎁 Free Value Worth £2,000·🇬🇧 Limited Time — UK Only·🎓 Free Learning for 1 Month·🤖 Free AI Training Included·📚 4,000+ Lessons · 35,000+ Quizzes·🏆 GCSE Mocks · Olympiad Papers·⚡ Selected Students Only · Limited Places·🎁 Free Value Worth £2,000·🇬🇧 Limited Time — UK Only·🎓 Free Learning for 1 Month·🤖 Free AI Training Included·📚 4,000+ Lessons · 35,000+ Quizzes·🏆 GCSE Mocks · Olympiad Papers·⚡ Selected Students Only · Limited Places·🎁 Free Value Worth £2,000·
JavaScript

Try and Catch

📚 What is Try/Catch in JavaScript? try/catch lets your JavaScript code handle errors gracefully. The code inside try runs normally. If anything throws an error, execution jumps to the catch block instead of crashing with an uncaught exception. The error object e has .message and .stack properties.

8 min 10 XP Lesson 11 of 21
Try and Catch
🌐

Appy Says…

API calls fail. Users type rubbish. Files don't load. In JavaScript, try/catch is how you handle the unexpected without crashing the whole page. Every professional JS developer uses this daily.

📖

What is try/catch?

JavaScript's try/catch lets you run risky code in a try block and handle errors gracefully in a catch block — preventing uncaught exceptions from breaking the user experience.

  • try { ... } catch (error) { ... } — basic structure
  • finally { ... } — always runs, whether or not an error occurred
  • The error object has .message and .name properties
  • throw new Error('Something went wrong') — throw your own errors
  • Async/await errors: wrap await calls in try/catch
  • Common errors: TypeError, ReferenceError, SyntaxError, RangeError
🎮

Think of it like a Roblox safe zone

In Roblox PvP games, a safe zone means you won't die there — bad things can happen but you're protected. try/catch is a safe zone for your code. Errors happen, but instead of dying (crashing), you handle them and carry on.

⚙️

How It Works

  • 1. JavaScript tries every statement in the try block
  • 2. The moment an error is thrown, execution jumps to catch
  • 3. catch (error) receives the Error object — inspect error.message
  • 4. finally runs no matter what — use it to clean up (close connections, hide spinners)
  • 5. For async: try { const data = await fetch(url); } catch (err) { ... }
  • 6. throw can rethrow: catch (e) { if (e.name !== 'NetworkError') throw e; }
🌍

Real-World Examples

  • Fetch request: try { const res = await fetch(url); } catch { showOfflineBanner(); }
  • JSON parsing: try { JSON.parse(badStr) } catch { return null; }
  • WhatsApp shows 'message not delivered' instead of crashing when network fails
  • Spotify falls back to cached songs when the stream request fails
  • YouTube catches subtitle load errors and shows 'CC unavailable' without breaking playback
💡

Key Facts

  • Unhandled promise rejections in async code used to silently disappear — always catch async errors
  • You can throw any value: throw 'error message', but throwing an Error object is best practice
  • window.onerror and window.addEventListener('unhandledrejection') catch global errors for logging
  • Error boundaries in React work on the same principle — try/catch for UI trees
⚠️

Watch Out!

Don't catch an error and do nothing: catch (e) {}. This silently swallows errors and makes debugging a nightmare. At minimum, console.error(e) — or better, show the user a friendly message and log to an error service.

📌

Remember

Any await call can reject. Wrap async code in try/catch. Always do something in catch — at minimum log the error.

What You Learned

  • try/catch/finally handles runtime errors without crashing the app
  • Wrap all await calls in try/catch — async errors are silent otherwise
  • Unlocks: resilient API calls, safe JSON parsing, offline-friendly apps

Key Facts

  • Unhandled promise rejections in async code used to silently disappear — always catch async errors
  • You can throw any value: throw 'error message', but throwing an Error object is best practice
  • window.onerror and window.addEventListener('unhandledrejection') catch global errors for logging
  • Error boundaries in React work on the same principle — try/catch for UI trees

Real-World Examples

• Fetch request: <code>try { const res = await fetch(url); } catch { showOfflineBanner(); }</code> • JSON parsing: <code>try { JSON.parse(badStr) } catch { return null; }</code> • WhatsApp shows 'message not delivered' instead of crashing when network fails • Spotify falls back to cached songs when the stream request fails • YouTube catches subtitle load errors and shows 'CC unavailable' without breaking playback

Remember

Any await call can reject. Wrap async code in try/catch. Always do something in catch — at minimum log the error.

Quick Quiz

1 / 2

try/catch is for?