0
0
Javascriptprogramming~30 mins

Throwing errors in Javascript - Mini Project: Build & Apply

Choose your learning style9 modes available
Throwing errors
πŸ“– Scenario: Imagine you are making a simple calculator app. You want to make sure users only enter numbers when they try to add two values. If they enter something else, you want to show a clear error message.
🎯 Goal: You will build a small program that checks if inputs are numbers. If not, it will throw an error with a helpful message.
πŸ“‹ What You'll Learn
Create two variables with exact names and values
Create a helper variable to check input types
Use throw new Error() to raise an error if inputs are not numbers
Print the result or error message
πŸ’‘ Why This Matters
🌍 Real World
Throwing errors helps programs stop when something goes wrong, so users get clear messages instead of confusing results.
πŸ’Ό Career
Understanding error handling is important for writing reliable code and debugging in real software projects.
Progress0 / 4 steps
1
Create input variables
Create two variables called input1 and input2. Set input1 to the number 10 and input2 to the string "five".
Javascript
Need a hint?

Use const to create variables. Remember to put quotes around strings.

2
Create a helper variable to check types
Create a variable called areNumbers that is true only if both input1 and input2 are numbers. Use the typeof operator to check each input.
Javascript
Need a hint?

Use typeof input1 === "number" and combine with && for both inputs.

3
Throw an error if inputs are not numbers
Write an if statement that checks if areNumbers is false. Inside the if, throw a new error with the message "Both inputs must be numbers". Otherwise, create a variable sum that adds input1 and input2.
Javascript
Need a hint?

Use throw new Error("message") inside the if block.

4
Print the result or catch the error
Wrap the previous code in a try block. In the try, calculate the sum as before. In the catch block, print the error message using console.log(error.message). If no error, print the sum with console.log(sum).
Javascript
Need a hint?

Use try { ... } catch (error) { ... } to handle errors and print messages.