Lecture Notes Of Day 12: Error Handling and Debugging in JavaScript

Rashmi Mishra
0

Lecture Notes Of Day 12
Error Handling and Debugging in JavaScript


Objective:

In today's lesson, we will focus on two key aspects of JavaScript development: debugging and error handling. By the end of this lesson, you will be able to:

  • Debug JavaScript code using various techniques.
  • Handle errors in your code using proper error handling methods.

Topics Covered:

1.  Using console.log() for debugging.

2.  The try...catch block for error handling.

3.  Common JavaScript errors and how to fix them.


1. Using console.log() for Debugging

What is Debugging?

Debugging is the process of identifying and fixing errors or bugs in your code. It's an essential skill for every programmer. Often, code doesn't behave the way you expect it to, and debugging helps you find out why.

Why use console.log()?

console.log() is one of the simplest and most commonly used methods to debug JavaScript. It allows you to print values to the console, making it easier to trace the flow of your program and see where things are going wrong.

How does it work? 

You can use console.log() to print out variables, check values during execution, or trace the sequence of code execution. 

Example:

let x = 10;

let y = 20;

let sum = x + y;

console.log('The value of x is:', x);  // Output: The value of x is: 10

console.log('The value of y is:', y);  // Output: The value of y is: 20

console.log('The sum is:', sum);       // Output: The sum is: 30

 

 You can also print more complex information like objects and arrays:

let person = {

  name: 'John',

  age: 30

};

 

console.log(person);  // Output: { name: 'John', age: 30 }

 

 Common uses of console.log() include:

  • Checking variable values at different points in your code.
  • Verifying if certain code blocks are being executed.
  • Tracing the flow of your program, especially in loops and conditional statements.

Tip: Remember to remove console.log() statements from your production code before deployment, as they can clutter the console and expose sensitive information.


2. The try...catch Block for Error Handling

What is an Error?

Errors are issues that occur in your code, typically causing it to stop running or behave incorrectly. JavaScript provides mechanisms to catch these errors and handle them gracefully, instead of letting your program crash.

The try...catch statement allows you to handle errors in a controlled way.

Syntax of try...catch:

try {

  // Code that may throw an error

} catch (error) {

  // Code to handle the error

}

  • The try block contains the code that might cause an error.
  • The catch block contains the code to handle the error if it occurs. You can access the error that was thrown in the catch block using the error parameter.

Example 1:

try {

  let result = 10 / 0; // This will throw an error

  console.log(result);

} catch (error) {

  console.log('An error occurred:', error);  // Output: An error occurred: Infinity

}

 

 In the example above, dividing by 0 results in Infinity (which is not an error in JavaScript but may be unexpected). This is captured in the catch block.

Example 2:

try {

  let person = null;

  console.log(person.name); // This will cause an error (cannot read property 'name' of null)

} catch (error) {

  console.log('Error:', error.message);  // Output: Error: Cannot read property 'name' of null

}

 

In this example, attempting to access a property on a null value causes a TypeError. The catch block catches the error and logs the error message.

Why use try...catch?

  • To prevent your program from crashing due to errors.
  • To provide feedback or fallback behavior when something goes wrong (e.g., display a user-friendly message).
  • To isolate potentially problematic code and handle errors where they occur, rather than letting them propagate throughout the entire program.

3. Common JavaScript Errors and How to Fix Them

In this section, we will go over some of the most common errors you will encounter in JavaScript and how to deal with them.

a) Syntax Errors:

These occur when there is a mistake in the way your code is written, such as missing parentheses, brackets, or commas.

Example:

let a = 5

console.log(a)

Fix:

Make sure you have all required syntax elements.

let a = 5;

console.log(a);

b) Reference Errors:

These happen when you try to use a variable that has not been defined.

Example:

console.log(x);  // ReferenceError: x is not defined

Fix:

Ensure that the variable is declared before you use it.

let x = 10;

console.log(x);  // Output: 10

c) Type Errors:

These occur when a value is not of the expected type.

Example:

let a = 'Hello';

a.push('World');  // TypeError: a.push is not a function

Fix:

Make sure you are performing operations on the correct type of value.

let a = ['Hello'];

a.push('World');  // Correct usage

console.log(a);  // Output: ['Hello', 'World']

d) Range Errors:

Range errors occur when a value is outside the allowable range for a function or operation.

Example:

let arr = new Array(-1);  // RangeError: Invalid array length

Fix:

Check that the values used in operations are within valid ranges.

let arr = new Array(10);  // Valid array length

e) Logic Errors:

Logic errors occur when your code runs without throwing errors but doesn't produce the expected results.

Example:

let a = 5;

let b = 10;

console.log(a - b);  // Output: -5 (But expected 15)

Fix:

Carefully review the logic in your code and verify that it matches the intended behavior.

let a = 5;

let b = 10;

console.log(a + b);  // Output: 15 (Corrected logic)


Conclusion

In Summary:

  • Use console.log() to check variable values and trace your code during debugging.
  • Use the try...catch block to handle errors gracefully and prevent your program from crashing.
  • Be aware of common JavaScript errors, including syntax errors, reference errors, type errors, range errors, and logic errors. Understanding these will help you write more robust and error-free code.

Assignment/Practice:

1.  Write a function that divides two numbers and uses try...catch to handle division by zero errors.

2.  Use console.log() to debug a program that sums the numbers in an array, ensuring that all numbers are integers.

 

Post a Comment

0Comments

Post a Comment (0)