📖 Scenario: Imagine you are building a simple calculator app that divides two numbers. Sometimes users might enter zero as the divisor, which causes an error. You want to handle this error gracefully.
🎯 Goal: You will create a program that tries to divide two numbers and uses a try-catch block to catch any errors, then display a friendly message.
📋 What You'll Learn
Create two variables called numerator and denominator with exact values 10 and 0
Create a variable called result and set it to null
Use a try block to divide numerator by denominator and assign to result
Use a catch block to catch any error and assign the string 'Cannot divide by zero' to result
Print the value of result
💡 Why This Matters
🌍 Real World
Try-catch blocks help apps avoid crashing when unexpected errors happen, like dividing by zero or reading missing files.
💼 Career
Understanding error handling is essential for writing reliable code in any software development job.
Progress0 / 4 steps
1
Create the numbers to divide
Create two variables called numerator and denominator with values 10 and 0 respectively.
Javascript
Hint
Use const to create variables and assign the exact numbers.
2
Create a variable to hold the result
Create a variable called result and set it to null.
Javascript
Hint
Use let because result will change later.
3
Use try-catch to divide safely
Use a try block to divide numerator by denominator and assign it to result. Use a catch block to catch any error and assign the string 'Cannot divide by zero' to result.
Javascript
Hint
Throw an error manually if denominator is zero, then catch it to set result.
4
Print the result
Write console.log(result) to display the value of result.
Javascript
Hint
Use console.log(result) to print the final message.
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
Step 1: Understand the role of try
The try block is used to run code that might throw an error during execution.
Step 2: Differentiate from other code blocks
Other options like declaring variables, loops, or functions are unrelated to error handling.
Final Answer:
To run code that might cause an error -> Option A
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?