Module 6: Errors, Debugging, and Troubleshooting
Lab: Error Handling and Debugging Practice
Practice using try...catch
to handle potential errors and use console.log
or the debugger
statement to inspect code.
Tasks to Complete:
- **Task 1 (Error Handling):** Modify the `divideNumbers` function. Wrap the division operation (`numerator / denominator`) in a `try` block. Add a `catch` block that catches any error. Inside the `catch` block, `console.error()` a user-friendly message like "Error: Cannot divide by zero." or "An error occurred during division: [error message]". If the division is successful (no error), `console.log()` the result as it currently does.
- **Task 2 (Debugging with `console.log`):** The `sumUpTo` function has a logical error. It's supposed to sum numbers from 1 up to `limit`. Add `console.log()` statements inside its `for` loop to inspect the values of `i` and `total` during each iteration. Identify the bug and fix it so it correctly calculates the sum. (Hint: The loop condition and the summation logic `total = i` are areas to inspect).
- **Task 3 (Optional - Using `debugger;`):** Uncomment the `debugExample` function. Place a `debugger;` statement inside its `for` loop. If you run this code in a browser with the Developer Tools open, the script execution should pause at the `debugger;` statement, allowing you to inspect variables and step through the code.
JavaScript Sandbox
Output will appear here...
JavaScript execution is sandboxed. Output from `console.log()` and errors will appear above.