Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

Discuss error handling in

JavaScript using suitable


example.
Frequency

Error Handling in JavaScript


Error handling is a crucial aspect of JavaScript programming, as it ensures that
your code can gracefully handle unexpected situations and continue to run
smoothly. JavaScript provides a try...catch statement for handling errors, which
allows you to catch and handle exceptions that occur during the execution of your
code. Additionally, throw can be used to create custom errors, and finally can be
used to execute code after try and catch , regardless of whether an error
occurred.

Syntax

try {
// Code that may throw an error
} catch (error) {
// Code to handle the error
} finally {
// Code that will always run, regardless of an error
}

Example of Error Handling


Below is a practical example that demonstrates how to use try...catch...finally to
handle errors in JavaScript.

HTML

Discuss error handling in JavaScript using suitable example. 1


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Error Handling Example</title>
<script src="app.js"></script>
</head>
<body>
<h1>Error Handling in JavaScript</h1>
<button onclick="executeWithErrorHandling()">Execute Code
</button>
<p id="output"></p>
</body>
</html>

JavaScript (app.js)

function executeWithErrorHandling() {
const outputElement = document.getElementById('output');
outputElement.innerHTML = ""; // Clear previous output

try {
// Code that may throw an error
let result = riskyOperation();
outputElement.innerHTML = "Operation successful: " +
result;
} catch (error) {
// Code to handle the error
outputElement.innerHTML = "An error occurred: " + err
or.message;
} finally {
// Code that will always run, regardless of an error
outputElement.innerHTML += "<br>Execution complete.";
}

Discuss error handling in JavaScript using suitable example. 2


}

function riskyOperation() {
// Simulate an error
let num = Math.random();
if (num < 0.5) {
throw new Error("Random error occurred!");
}
return num;
}

Explanation
1. HTML Structure:

A button to trigger the JavaScript function executeWithErrorHandling() .

A paragraph element to display the output or error message.

2. JavaScript Code:

executeWithErrorHandling Function:

Clears any previous output in the paragraph element.

try Block: Calls the riskyOperation function, which may throw an error.
If the operation is successful, it displays the result.

catchBlock: Catches any errors thrown in the try block and displays
an error message.

Block: Appends a message indicating that execution is


finally

complete, which runs regardless of whether an error occurred.

3. riskyOperation Function:

Generates a random number.

If the number is less than 0.5, it throws a new error with a custom
message.

If no error occurs, it returns the random number.

Discuss error handling in JavaScript using suitable example. 3


Benefits of Error Handling
Graceful Degradation: Allows your program to continue running or fail
gracefully rather than crashing abruptly.

Debugging: Helps in identifying and debugging issues by providing


informative error messages.

User Experience: Enhances user experience by providing meaningful


feedback instead of generic error messages or blank screens.

Custom Error Throwing


In addition to handling built-in errors, you can create and throw custom errors
using the throw statement. This is useful when you want to enforce certain
conditions or handle specific error scenarios.

Example:

function validateAge(age) {
if (age < 0 || age > 120) {
throw new Error("Invalid age provided!");
}
return "Valid age: " + age;
}

try {
console.log(validateAge(25)); // Valid case
console.log(validateAge(-5)); // Invalid case, will thro
w an error
} catch (error) {
console.error("Error: " + error.message);
}

Explanation:

The validateAge function checks if the provided age is within a valid range.

If the age is invalid, it throws a custom error.

Discuss error handling in JavaScript using suitable example. 4


The try block attempts to validate ages, and the catch block handles any
errors that are thrown, logging an error message to the console.

By understanding and utilizing error handling in JavaScript, you can write more
robust and reliable code that can gracefully handle unexpected situations and
provide meaningful feedback to users and developers.

Discuss error handling in JavaScript using suitable example. 5

You might also like