0
0
Javascriptprogramming~15 mins

Try–catch block in Javascript - Mini Project: Build & Apply

Choose your learning style9 modes available
Handling Errors with Try-Catch Block
📖 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
Need a 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
Need a 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
Need a 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
Need a hint?

Use console.log(result) to print the final message.