Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Error Handling in JS - Compressed

Uploaded by

shubhangiv05
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Error Handling in JS - Compressed

Uploaded by

shubhangiv05
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Error Handling in JS

Assignment Solutions
Assignment Solutions
Answer the following questions briefly

a. What is error handling in JavaScript, and why is it important?

b. What is the purpose of try...catch statements in JavaScript?


Ans)
a. Error handling in JavaScript involves managing and responding to runtime errors that may occur during the
execution of a program. Errors can be caused by various factors such as incorrect input, unexpected
conditions, or network issues.

Proper error handling is crucial for maintaining the stability and reliability of a JavaScript application. It
prevents unexpected crashes, provides meaningful feedback to developers during debugging, and
enhances the user experience by gracefully handling issues without abrupt failures.

b. The try...catch statement in JavaScript is used to handle exceptions or errors that may occur within a block
of code. The try block contains the code that might throw an exception, and the catch block specifies what
to do if an exception is thrown.

If an error occurs within the try block, the control is transferred to the corresponding catch block. This allows
developers to handle errors gracefully, log diagnostic information, and take appropriate actions to prevent
the application from crashing.

Using try...catch promotes robust error handling, making it possible to identify and respond to errors without
disrupting the overall flow of the application.

Answer the following questions briefly

a. What is the role of the throw statement in error handling?

b. How can you create custom error objects in JavaScript, and why would you want to do this?
Ans)
a. The throw statement in JavaScript is used to manually generate an exception or error. When a specific
condition is not met, or an error is detected, the throw statement allows developers to interrupt the normal
flow of the program and trigger an exception.

The throw statement is often used in conjunction with try...catch blocks to handle exceptions gracefully. It
allows developers to create more meaningful error messages and communicate the nature of the error to
aid in debugging.

b. In JavaScript, you can create custom error objects by extending the built-in Error constructor. This allows you
to define your own error types with specific properties and behaviors.

Full Stack Web Development


Assignment Solutions

Custom errors provide clearer information about the nature of the error. Developers can distinguish between
different types of errors and handle them appropriately.

Creating a hierarchy of custom errors allows for more organized and structured error handling in complex
applications.

Custom errors can carry additional information, aiding in debugging and providing insights into the cause of
the error.

Write a JavaScript function called calculateAverage that takes an array of numbers as an argument. This
function should calculate and return the average of the numbers in the array. However, you should
implement error handling in the following scenarios:
a. If the input argument is not an array, throw a CustomError with code 400 and the message "Input must be
an array."

b. If the array is empty, throw a CustomError with code 401 and the message "Array must not be empty."

c. If any element in the array is not a number, throw a CustomError with code 402 and the message "Array
must contain only numbers."

d. Handle these custom errors gracefully in your code and provide helpful error messages.

Full Stack Web Development


Assignment Solutions
Ans)

class CustomError extends Error {

constructor(code, message) {

super(message);

this.code = code;

function calculateAverage(numbers) {

// a. Check if the input is an array

if (!Array.isArray(numbers)) {

throw new CustomError(400, "Input must be an array.");

// b. Check if the array is empty

if (numbers.length === 0) {

throw new CustomError(401, "Array must not be empty.");

// c. Check if the array contains only numbers

if (!numbers.every((num) => typeof num === 'number')) {

throw new CustomError(402, "Array must contain only numbers.");

// Calculate the average

const sum = numbers.reduce((acc, num) => acc + num, 0);

const average = sum / numbers.length;

return average;

// Example usage:

try {

const numbers = [1, 2, 3, 4, 5];

const result = calculateAverage(numbers);

console.log("Average:", result);

} catch (error) {

if (error instanceof CustomError) {

console.error(`Error ${error.code}: ${error.message}`);

} else {

console.error("Unexpected error:", error.message);

You are tasked with creating a form validation function in JavaScript for a user registration form. The
form contains fields for username, email, and password. Your goal is to implement error handling to
validate user input and display appropriate error messages.

Full Stack Web Development


Assignment Solutions
a. Create a JavaScript function validateForm that takes the form of input values as parameters.

b. Perform the following validations:

i. Ensure the username field is not empty and has a minimum length of 3 characters.

ii. Validate the email field to ensure it contains a valid email format (e.g., user@example.com).

iii. Check the password field for a minimum length of 6 characters.

c. If any of the validations fail, throw custom error objects specific to each validation.

d. Use a try...catch block within the validateForm function to catch and handle any thrown errors.

e. Display appropriate error messages next to the respective form fields.

class ValidationError extends Error {

constructor(field, message) {

super(message);

this.field = field;

function validateForm(username, email, password) {

try {

// Validate username

if (!username || username.length < 3) {

throw new ValidationError("username", "Username must be at


least 3 characters long.");

// Validate email

const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

if (!email || !email.match(emailRegex)) {

throw new ValidationError("email", "Invalid email format.");

// Validate password

if (!password || password.length < 6) {

throw new ValidationError("password", "Password must be at


least 6 characters long.");

// If all validations pass, return true or perform further


actions

return true;

} catch (error) {

// Handle and display errors

if (error instanceof ValidationError) {

displayError(error.field, error.message);

} else {

// Handle unexpected errors

console.error("Unexpected error:", error.message);

Full Stack Web Development


Assignment Solutions
// Return false or perform other error-handling actions

return false;

// Example function to display error messages next to form fields

function displayError(field, message) {

const errorMassage = field + ":" + message

if (errorMassage) {

console.log(errorMassage)

// Example usage:

const username = "user123";

const email = "user@example";

const password = "pass";

validateForm(username, email, password);


Full Stack Web Development

You might also like