Assignments on Day 12 :Error Handling and Debugging in JavaScript

Rashmi Mishra
0

  Assignments Of Day 12: Error Handling and Debugging in JavaScript


Assignments on Day 12 :Error Handling and Debugging in JavaScript


Assignment 1: Using console.log() to Debug

Problem:

You have the following code, but it's not working as expected. Use console.log() to find the issue and fix it.

javascript

Copy code

function calculateArea(radius) {

  let area = Math.PI * radius * radius;

  return area;

}

 

let radius = 5;

let result = calculateArea(radius);

console.log('The area is: ', result);

Task:

  • Add console.log() statements to check the values of radius and area inside the function.
  • Verify if the result matches the expected output.

Solution:

javascript

Copy code

function calculateArea(radius) {

  console.log('Radius inside function: ', radius);  // Debugging: Check radius value

  let area = Math.PI * radius * radius;

  console.log('Area inside function: ', area);  // Debugging: Check area value

  return area;

}

 

let radius = 5;

let result = calculateArea(radius);

console.log('The area is: ', result);

Explanation:

  • The console.log() inside the calculateArea function will help us verify the values of radius and area.
  • This way, we can trace the values during execution and ensure that the calculation is correct.

Assignment 2: Handling Division by Zero with try...catch

Problem:

Write a function that divides two numbers. Use a try...catch block to handle division by zero errors. If division by zero occurs, display a friendly error message.

javascript

Copy code

function divideNumbers(a, b) {

  let result = a / b;

  return result;

}

 

let num1 = 10;

let num2 = 0;

 

let divisionResult = divideNumbers(num1, num2);

console.log('The result is:', divisionResult);

Task:

  • Use try...catch to handle the case where b is zero and prevent the program from crashing.
  • Return a custom error message when division by zero is detected.

Solution:

javascript

Copy code

function divideNumbers(a, b) {

  try {

    if (b === 0) {

      throw new Error('Cannot divide by zero!');

    }

    let result = a / b;

    return result;

  } catch (error) {

    console.log('Error:', error.message);  // Display error message

    return null;  // Return null when an error occurs

  }

}

 

let num1 = 10;

let num2 = 0;

 

let divisionResult = divideNumbers(num1, num2);

if (divisionResult !== null) {

  console.log('The result is:', divisionResult);

} else {

  console.log('An error occurred while dividing.');

}

Explanation:

  • The try block checks if b is zero. If it is, an error is thrown using throw new Error().
  • The catch block catches the error and logs the custom error message (Cannot divide by zero!).
  • The null return value ensures that we don't attempt to display an invalid result.

Assignment 3: Fixing Reference Error Using try...catch

Problem:

In the following code, a ReferenceError occurs because a variable is accessed before it is defined. Use try...catch to handle this error.

javascript

Copy code

function displayMessage() {

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

}

 

displayMessage();

Task:

  • Modify the code to handle the ReferenceError using a try...catch block and log a custom error message.

Solution:

javascript

Copy code

function displayMessage() {

  try {

    console.log(message);  // This will throw a ReferenceError

  } catch (error) {

    console.log('Error:', error.message);  // Display custom error message

  }

}

 

displayMessage();

Explanation:

  • The try...catch block catches the ReferenceError and logs the error message (message is not defined).
  • This prevents the program from crashing and helps us manage errors effectively.

Assignment 4: Debugging a Type Error

Problem:

You have the following code, but it's throwing a TypeError. Use console.log() to debug and identify the cause of the error.

javascript

Copy code

let str = 'Hello, ';

let num = 10;

 

let result = str + num.push(5);  // TypeError: num.push is not a function

console.log(result);

Task:

  • Use console.log() to debug the error and correct the issue. The goal is to concatenate the number 5 to the string str correctly.

Solution:

javascript

Copy code

let str = 'Hello, ';

let num = [10];

 

console.log('str:', str);  // Debugging: Check value of str

console.log('num:', num);  // Debugging: Check value of num

 

let result = str + num.push(5);  // This is incorrect

console.log('Result:', result);  // Check the result after fixing

 

// Correct way:

let resultFixed = str + num.join(', ');  // Concatenate the number with the string

console.log('Fixed result:', resultFixed);  // Output: Hello, 10, 5

Explanation:

  • The original code attempted to call push() on a number, which caused the TypeError. push() is a method for arrays, not numbers.
  • After fixing the issue, the join() method is used on the array num to concatenate the numbers correctly.

Assignment 5: Handling RangeError

Problem:

You are creating an array with a negative size, which will cause a RangeError. Use a try...catch block to handle the error.

javascript

Copy code

function createArray(size) {

  let arr = new Array(size);  // RangeError if size is negative

  return arr;

}

 

let array = createArray(-5);  // This will throw RangeError

console.log(array);

Task:

  • Use try...catch to handle the RangeError and display a message when the size is negative.

Solution:

javascript

Copy code

function createArray(size) {

  try {

    if (size < 0) {

      throw new RangeError('Array size cannot be negative.');

    }

    let arr = new Array(size);

    return arr;

  } catch (error) {

    console.log('Error:', error.message);  // Display error message

    return null;  // Return null if error occurs

  }

}

 

let array = createArray(-5);  // This will trigger the RangeError

console.log(array);  // Output: Error: Array size cannot be negative.

Explanation:

  • A RangeError is thrown if the size of the array is negative.
  • The catch block catches this error and logs a custom error message (Array size cannot be negative).



Post a Comment

0Comments

Post a Comment (0)