Sometimes programs make mistakes while running. Catching runtime errors helps stop the program from crashing and lets you handle problems smoothly.
Catching runtime errors in Javascript
try { // code that might cause an error } catch (error) { // code to handle the error }
The try block contains code that might cause an error.
The catch block runs only if there is an error inside try.
catch is not triggered.try { let result = 10 / 0; console.log(result); } catch (error) { console.log('Error caught:', error.message); }
catch.try { JSON.parse('invalid json'); } catch (error) { console.log('Caught error:', error.message); }
catch.try { nonExistentFunction(); } catch (error) { console.log('Oops! Function not found.'); }
This program tries to read user input as JSON. Because the input is broken, it throws an error. The catch block catches it and prints a friendly message.
try { let userInput = '{"name": "Alice"'; // missing closing brace let user = JSON.parse(userInput); console.log('User name:', user.name); } catch (error) { console.log('There was a problem parsing user input:', error.message); }
Always use try...catch around code that might fail to keep your program running smoothly.
You can access the error message with error.message inside the catch block.
Use finally block if you want to run code no matter what, after try and catch.
Catching runtime errors helps your program handle problems without crashing.
Use try to run risky code and catch to handle errors.
This makes your program more friendly and reliable.
Practice
What is the main purpose of using try and catch in JavaScript?
Solution
Step 1: Understand the role of
Thetryblocktryblock runs code that might cause an error.Step 2: Understand the role of
Thecatchblockcatchblock handles any error from thetryblock to keep the program running smoothly.Final Answer:
To handle errors and prevent the program from crashing -> Option CQuick Check:
try-catch = error handling [OK]
- Thinking try-catch speeds up code
- Using try-catch to create variables
- Confusing try-catch with loops
Which of the following is the correct syntax to catch errors in JavaScript?
try {
// code
} catch (error) {
// handle error
}Solution
Step 1: Check the
Thetryblock syntaxtryblock must be followed bycatchwith parentheses around the error variable.Step 2: Verify the
The correct syntax iscatchblock syntaxcatch (error) { }with parentheses around the error parameter.Final Answer:
try { } catch (error) { } -> Option AQuick Check:
catch needs parentheses [OK]
- Omitting parentheses in catch
- Using parentheses after try
- Adding parentheses after catch keyword
What will be the output of the following code?
try {
let result = 10 / 0;
console.log(result);
} catch (e) {
console.log('Error caught');
}Solution
Step 1: Understand division by zero in JavaScript
Dividing 10 by 0 does not cause an error; it results inInfinity.Step 2: Check if catch block runs
Since no error occurs, thecatchblock is skipped andInfinityis logged.Final Answer:
Infinity -> Option AQuick Check:
10/0 = Infinity, no error [OK]
- Assuming division by zero throws error
- Expecting catch block to run
- Confusing 0 with Infinity
Find the error in this code and choose the correct fix:
try {
console.log(x);
} catch e {
console.log('Error:', e.message);
}Solution
Step 1: Identify syntax error in catch block
The catch block must have parentheses around the error variable, socatch eis invalid syntax.Step 2: Correct the catch syntax
Changing it tocatch (e)fixes the syntax and allows error handling.Final Answer:
Change catch e to catch (e) -> Option BQuick Check:
Catch needs parentheses around error [OK]
- Omitting parentheses in catch
- Adding finally when not needed
- Ignoring undeclared variable error
You want to safely parse JSON data that might be invalid. Which code snippet correctly catches parsing errors?
const jsonString = '{"name": "Alice", age: 25}';
try {
const data = JSON.parse(jsonString);
console.log(data.name);
} catch (error) {
console.log('Invalid JSON:', error.message);
}Solution
Step 1: Understand JSON.parse behavior
JSON.parse throws an error if the JSON string is invalid, like missing quotes around keys.Step 2: Check try-catch usage
The try block runs JSON.parse, and the catch block handles any parsing error to avoid crashing.Final Answer:
This code correctly catches JSON parsing errors and logs a message -> Option DQuick Check:
try-catch handles JSON.parse errors [OK]
- Assuming JSON.parse never throws errors
- Placing catch block incorrectly
- Using if-else instead of try-catch for errors
Ready to prove it?
Pass the test and this pattern moves unknown
