Bird
Raised Fist0
Javascriptprogramming~10 mins

Try–catch block in Javascript - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Try–catch block
Start
↓
Try block runs
↓
Error?
No→Try block ends normally
|Yes↓
Catch block runs
↓
Continue after catch
↓
End
The program tries to run code inside the try block. If an error happens, it jumps to the catch block to handle it, then continues.
Execution Sample
Javascript
try {
  let result = 10 / 0;
  console.log('Result:', result);
} catch (error) {
  console.log('Error caught:', error.message);
}
This code tries to divide 10 by 0 and print the result. If an error occurs, it catches and prints the error message.
Execution Table
StepActionEvaluationResult
1Enter try blockNo error yetContinue
2Calculate 10 / 0Division by zero in JS returns Infinityresult = Infinity
3console.log('Result:', result)Prints 'Result: Infinity'Output: Result: Infinity
4Try block endsNo error thrownSkip catch block
5Program continues after try-catchNormal flowEnd
💡 Try block completed without error, so catch block is skipped.
Variable Tracker
VariableStartAfter Step 2Final
resultundefinedInfinityInfinity
errorundefinedundefinedundefined
Key Moments - 2 Insights
Why doesn't the catch block run when dividing by zero?
In JavaScript, dividing by zero does not throw an error; it returns Infinity. So the try block finishes normally and the catch block is skipped, as shown in execution_table step 4.
What happens if an error is thrown inside the try block?
If an error occurs, execution immediately jumps to the catch block to handle it. This is not shown here but would appear as a jump from try to catch in the flow.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'result' after step 2?
AInfinity
B0
CError
Dundefined
💡 Hint
Check the 'Evaluation' and 'Result' columns in row 2 of the execution_table.
At which step does the catch block run in this example?
AStep 3
BStep 4
CNever
DStep 5
💡 Hint
Look at the 'Result' column in step 4; it says 'Skip catch block'.
If the code inside try threw an error, what would happen next?
AThe program would crash immediately
BThe catch block would run to handle the error
CThe try block would continue running
DNothing changes, catch block is ignored
💡 Hint
Refer to the concept_flow where error leads to catch block execution.
Concept Snapshot
try {
  // code that might fail
} catch (error) {
  // code to handle error
}

- Runs try block code
- If error occurs, jumps to catch
- catch receives error object
- After catch, program continues normally
Full Transcript
A try-catch block lets your program try to run code that might cause an error. If an error happens, the program jumps to the catch block to handle it without crashing. In JavaScript, some things like dividing by zero do not cause errors but return special values like Infinity, so catch does not run. The try block runs first, and if no error occurs, the catch block is skipped. If an error happens, the catch block runs with the error details. After catch, the program continues normally.

Practice

(1/5)
1.

What is the main purpose of a try block in JavaScript?

easy
A. To run code that might cause an error
B. To declare variables
C. To create loops
D. To define functions

Solution

  1. Step 1: Understand the role of try

    The try block is used to run code that might throw an error during execution.
  2. Step 2: Differentiate from other code blocks

    Other options like declaring variables, loops, or functions are unrelated to error handling.
  3. Final Answer:

    To run code that might cause an error -> Option A
  4. Quick Check:

    try runs risky code [OK]
Hint: Try block runs risky code safely [OK]
Common Mistakes:
  • Thinking try declares variables
  • Confusing try with loops
  • Assuming try defines functions
2.

Which of the following is the correct syntax to start a try-catch block in JavaScript?

?
easy
A. try: { /* code */ } catch: { /* handle error */ }
B. try { /* code */ } catch (error) { /* handle error */ }
C. try (/* code */) catch (error) { /* handle error */ }
D. try { /* code */ } catch error { /* handle error */ }

Solution

  1. Step 1: Recall correct try-catch syntax

    The correct syntax uses curly braces and parentheses for catch: try { ... } catch (error) { ... }.
  2. Step 2: Identify syntax errors in other options

    Options B, C, and D misuse colons, parentheses, or omit parentheses around the error parameter.
  3. Final Answer:

    try { /* code */ } catch (error) { /* handle error */ } -> Option B
  4. Quick Check:

    Curly braces and catch(error) needed [OK]
Hint: Catch needs parentheses around error [OK]
Common Mistakes:
  • Using colons instead of braces
  • Omitting parentheses in catch
  • Using parentheses after try
3.

What will be the output of the following code?

try {
  console.log('Start');
  throw new Error('Oops');
  console.log('End');
} catch (e) {
  console.log('Caught:', e.message);
}
medium
A. Start\nEnd
B. Start
C. Caught: Oops
D. Start\nCaught: Oops

Solution

  1. Step 1: Trace code inside try block

    The first console logs 'Start'. Then an error is thrown, so the next console.log('End') is skipped.
  2. Step 2: Catch block runs after error

    The catch block catches the error and logs 'Caught: Oops'.
  3. Final Answer:

    Start\nCaught: Oops -> Option D
  4. Quick Check:

    Error stops try, catch logs message [OK]
Hint: Error stops try; catch runs next [OK]
Common Mistakes:
  • Thinking code after throw runs
  • Ignoring catch block output
  • Confusing error message with error object
4.

Find the error in this code snippet:

try {
  console.log('Hello');
} catch e {
  console.log('Error:', e);
}
medium
A. Missing parentheses around e in catch
B. Missing semicolon after console.log
C. Try block cannot have console.log
D. Catch block must come before try

Solution

  1. Step 1: Check catch syntax

    The catch block must have parentheses around the error variable: catch (e).
  2. Step 2: Verify other parts

    Semicolons are optional in JavaScript; console.log is allowed in try; catch must come after try.
  3. Final Answer:

    Missing parentheses around e in catch -> Option A
  4. Quick Check:

    Catch needs (error) [OK]
Hint: Catch always needs parentheses around error [OK]
Common Mistakes:
  • Omitting parentheses in catch
  • Thinking semicolons are mandatory here
  • Reversing try and catch order
5.

You want to safely parse a JSON string that might be invalid. Which code correctly uses try-catch to handle errors and return null if parsing fails?

?
hard
A. try { JSON.parse(str); } catch { return null; }
B. try { return JSON.parse(str); } catch e { return null; }
C. try { return JSON.parse(str); } catch (e) { return null; }
D. try { return JSON.parse(str); } catch (e) { throw null; }

Solution

  1. Step 1: Understand JSON parsing risks

    Parsing invalid JSON throws an error, so we use try-catch to handle it safely.
  2. Step 2: Check correct catch syntax and behavior

    try { return JSON.parse(str); } catch (e) { return null; } uses correct catch syntax with (e) and returns null on error, which is the goal.
  3. Step 3: Identify errors in other options

    try { JSON.parse(str); } catch { return null; } misses return before JSON.parse(str), so returns undefined on success. try { return JSON.parse(str); } catch e { return null; } has syntax error (catch e needs catch (e)). try { return JSON.parse(str); } catch (e) { throw null; } throws null instead of returning it.
  4. Final Answer:

    try { return JSON.parse(str); } catch (e) { return null; } -> Option C
  5. Quick Check:

    Catch error with (e), return null on failure [OK]
Hint: Catch error with (e), return null on failure [OK]
Common Mistakes:
  • Omitting parentheses in catch
  • Throwing instead of returning null
  • Assuming catch without parameter always works
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard