MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
try...catch0%
Study Materials
JavaScript for IntermediateProgress 0%
1.1Block Scope with let & const1.2Template Literals1.3Destructuring Arrays and Objects1.4Default Parameters1.5Enhanced Object Literals
9.1try...catch9.2finally block9.3Throwing Custom Errors9.4Error Handling in Async Code
HomeTutorialsJavaScript for Intermediatetry...catch
finally block

try...catch

Beginner12 min read•Updated: 2026-09-15•By Er. Sumit Kumar (MSK Institute)
Study Materials

Errors in software applications are inevitable—from unexpected user inputs to malformed JSON payloads and network failures. Rather than letting unhandled exceptions crash your entire application, the try...catch statement allows developers to intercept runtime errors and recover gracefully.


1. Syntax & Core Flow

1try {
2 // Code that may throw an exception
3 const data = JSON.parse(rawString);
4 processData(data);
5} catch (error) {
6 // Executes ONLY if an exception is thrown inside the try block
7 console.error('Failed to parse data:', error.message);
8}

2. The Error Object

When an exception occurs, JavaScript instantiates an Error object passed to the catch block with three primary properties:

  • error.name: The error classification type (e.g., ReferenceError, TypeError, SyntaxError).
  • error.message: A human-readable description of what went wrong.
  • error.stack: A detailed stack trace of function calls indicating the exact file and line number.
1try {
2 const result = undefinedVariable + 10;
3} catch (err) {
4 console.log('Error Name:', err.name); // 'ReferenceError'
5 console.log('Error Message:', err.message); // 'undefinedVariable is not defined'
6 console.log('Stack Trace:', err.stack);
7}

3. Standard Built-in Error Types

Error TypeTriggered When...Example
TypeErrorOperation executed on inappropriate typenull.toUpperCase()
ReferenceErrorAccessing an undeclared variableconsole.log(foo)
SyntaxErrorInvalid JavaScript or malformed JSONJSON.parse('{bad_json}')
RangeErrorNumeric value falls outside allowable rangenew Array(-1)
URIErrorMalformed URI passed to decodeURIComponent()decodeURIComponent('%')

4. Optional Catch Binding (ES2019)

In earlier versions of JavaScript, you were required to declare an error parameter: catch (e). In ES2019+, if the error details are not needed, you can omit the parameter completely:

1// Modern concise syntax:
2try {
3 return JSON.parse(cachedData);
4} catch {
5 // Error variable omitted because we only care that it failed
6 return null;
7}

5. Limitations: try...catch CANNOT Catch Asynchronous Callback Errors!

A classic pitfall: try...catch is synchronous. It cannot catch errors thrown inside asynchronous callbacks (like setTimeout or event listeners) because the try block finishes executing before the callback is fired!

1// FAILS TO CATCH!
2try {
3 setTimeout(() => {
4 throw new Error('Boom!'); // CRASHES! try block has already completed!
5 }, 1000);
6} catch (err) {
7 console.log('This will NEVER be reached!');
8}

(Note: To catch errors in asynchronous code, use .catch() on Promises or wrap await expressions inside try...catch).


Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What happens when an error is thrown inside a try block?
Question 2
What type of error is thrown when calling a method on null or undefined (e.g., null.trim())?
Question 3
What feature introduced in ES2019 allows catch blocks to omit the error parameter?
Question 4
Why can a synchronous try...catch NOT catch an error thrown inside a setTimeout callback?
Question 5
Which property of an Error object provides the line-by-line sequence of function calls that led to the exception?
Next Lesson

finally block

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Mini Project: Random Joke Generatorfinally block

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master JavaScript for Intermediate with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext