Error Handling and Debugging in JavaScript
Overview and Objectives
In this lab, learners will focus on identifying, debugging, and gracefully handling errors in JavaScript. You will:
- Practice debugging a provided faulty code snippet by identifying and correcting syntax and logical errors.
- Enhance a function by incorporating error handling using
try...catch
. - Use debugging techniques such as
console.log()
and thedebugger
statement to trace code execution.
By the end of this lab, you will be able to:
- Identify and fix common JavaScript errors.
- Implement proper exception handling to prevent your code from crashing.
- Improve code robustness and clarity through debugging and error management.
Tasks and Instructions
Task 1: Debugging a Faulty Code Snippet
-
Review the Provided Code:
Below is a code snippet with one or more deliberate errors. Copy the snippet into a new file nameddebuggingLab.js
.// Faulty Code Snippet: Debug and fix the errors function greetUser(name) { console.log("Hello, " + Name); // Error: 'Name' should be 'name' } function divideNumbers(a, b) { // Incorrect conditional: using assignment instead of comparison if (b = 0) { return "Cannot divide by zero"; } return a / b; } greetUser("Alice"); console.log("Division result: " + divideNumbers(10, 0));
-
Identify and Correct Errors:
- Error in
greetUser
: The variable used in concatenation isName
(uppercase), but the parameter isname
(lowercase). - Error in
divideNumbers
: The conditionif (b = 0)
uses assignment instead of comparison. It should use==
or===
.
- Error in
-
Fix the Code:
Update the code with the necessary corrections so that:- The
greetUser
function correctly prints"Hello, Alice"
. - The
divideNumbers
function properly checks for division by zero and returns the appropriate message.
- The
-
Test the Fixed Code:
Run the corrected code in your browser’s developer console or Node.js to confirm that it works as expected.
Task 2: Implementing Exception Handling with try…catch
-
Create a New Function:
In the same file or a new file (e.g.,errorHandlingLab.js
), write a functionsafeDivide(a, b)
that:- Checks if
b
is zero. If so, it should throw a custom error usingthrow new Error("Division by zero is not allowed.")
. - Otherwise, returns the result of
a / b
.
- Checks if
-
Wrap the Function Call in a try…catch Block:
- Call
safeDivide()
with a sample input that will trigger the error (e.g.,safeDivide(10, 0)
). - Use a
try...catch
block to catch the error and display a friendly error message usingconsole.error()
oralert()
.
Example structure:
function safeDivide(a, b) { if (b === 0) { throw new Error("Division by zero is not allowed."); } return a / b; } try { let result = safeDivide(10, 0); console.log("Result is: " + result); } catch (error) { console.error("Error encountered: " + error.message); }
- Call
-
Test Your Implementation:
Ensure that:- When calling
safeDivide(10, 0)
, the error is caught and the message"Error encountered: Division by zero is not allowed."
is displayed. - When calling
safeDivide(10, 2)
, the correct result (i.e.,5
) is printed to the console.
- When calling
Submission Criteria
The following should be included within a GitHub repository, and submitted via Canvas:
-
Files/Links:
- Submit the
debuggingLab.js
file containing your corrected code snippet. - Submit the
errorHandlingLab.js
file (or include both tasks in a single file) demonstrating your implementation ofsafeDivide
with exception handling.
- Submit the
-
Evidence of Output:
- Provide screenshots or text logs showing the console output for both the debugging task (with corrected output) and the try…catch implementation.
-
Error-Free Execution:
- Ensure your code runs without runtime errors and that error messages are clear and informative.
Grading Rubric
Criteria | Points | Description |
---|---|---|
Debugging Task - Error Identification | 10 pts | Correctly identifies the error in greetUser (case sensitivity) and in divideNumbers (assignment vs. comparison). |
Debugging Task - Code Correction | 10 pts | The code is correctly updated so that greetUser prints the correct greeting and divideNumbers properly handles division by zero. |
Exception Handling - Implementation | 5 pts | safeDivide correctly throws an error when b is zero, and returns a correct division result otherwise. |
Exception Handling - try…catch Usage | 5 pts | Properly uses a try…catch block to catch errors from safeDivide , and displays a user-friendly error message. |
Total Points: 30 points
Partial credit will be awarded for submissions that demonstrate a clear understanding of error handling and debugging concepts even if some elements are incomplete or contain minor errors. For example, if the debugging task is partially corrected (one error fixed but not the other), points will be deducted proportionally. Similarly, if the safeDivide
function is implemented correctly but the try…catch block is missing or partially implemented, partial credit will be given for the correct portions. Credit will be awarded based on the overall clarity of the approach, correct use of exception handling syntax, and the functionality of the final code.