0% found this document useful (0 votes)
5 views7 pages

Error Handling in JavaScript

Error Handling In Java Script

Uploaded by

SathishSathya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views7 pages

Error Handling in JavaScript

Error Handling In Java Script

Uploaded by

SathishSathya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Error Handling in JavaScript

1. Types of Errors

 Syntax Errors: Occur when there is a mistake in the syntax of the code (e.g., missing
parentheses).

 Runtime Errors: Occur during the execution of the code, often due to bad data or operations
(e.g., trying to call a non-function).

 Logical Errors: Occur when the code runs but produces incorrect results (e.g., incorrect
calculations).

2. Error Objects

JavaScript has a built-in Error object that contains the following properties:

 name: Type of the error (e.g., TypeError, ReferenceError).

 message: Description of the error.

 stack: Stack trace that shows the point in the code where the error occurred.

3. Error Handling Techniques

 Try...Catch Statement:

o Allows you to handle exceptions gracefully.

o Syntax:

javascript

Copy code

try { Error Handling in JavaScript

1. Types of Errors

 Syntax Errors: Occur when there is a mistake in the syntax of the code (e.g., missing
parentheses).

 Runtime Errors: Occur during the execution of the code, often due to bad data or operations
(e.g., trying to call a non-function).

 Logical Errors: Occur when the code runs but produces incorrect results (e.g., incorrect
calculations).

2. Error Objects

JavaScript has a built-in Error object that contains the following properties:

 name: Type of the error (e.g., TypeError, ReferenceError).

 message: Description of the error.

 stack: Stack trace that shows the point in the code where the error occurred.

3. Error Handling Techniques


 Try...Catch Statement:

o Allows you to handle exceptions gracefully.

o Syntax:

javascript

Copy code

try {

// Code that may throw an error

} catch (error) {

// Code to handle the error

console.error(error.message);

} finally {

// Code that will run regardless of an error occurring

o The finally block is optional and executes after the try and catch blocks.

 Throwing Errors:

o You can create and throw your own errors using the throw statement.

o Example:

javascript

Copy code

function checkValue(value) {

if (value < 0) {

throw new Error("Value must be non-negative");

return value;

4. Asynchronous Error Handling

 Promise Rejection: Use catch() to handle errors in promises.

javascript

Copy code

fetch('some-url')

.then(response => {
if (!response.ok) {

throw new Error('Network response was not ok');

return response.json();

})

.catch(error => console.error('Fetch error:', error));

 Async/Await: Use try...catch within async functions.

javascript

Copy code

async function fetchData() {

try {

const response = await fetch('some-url');

if (!response.ok) throw new Error('Network response was not ok');

const data = await response.json();

return data;

} catch (error) {

console.error('Error fetching data:', error);

5. Best Practices

 Always handle errors to prevent application crashes.

 Log errors to understand what went wrong.

 Provide user-friendly error messages.

 Validate inputs to avoid common errors.

Example Code

Here’s a simple example that incorporates various error handling techniques:

javascript

Copy code

function processInput(input) {

try {

if (typeof input !== 'number') {


throw new TypeError("Input must be a number");

// Simulate an operation that may fail

if (input < 0) {

throw new RangeError("Input must be non-negative");

console.log("Processing input:", input);

} catch (error) {

if (error instanceof TypeError) {

console.error("Type Error:", error.message);

} else if (error instanceof RangeError) {

console.error("Range Error:", error.message);

} else {

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

// Example usage

processInput(-5); // Logs: Range Error: Input must be non-negative

processInput("test"); // Logs: Type Error: Input must be a number

// Code that may throw an error

} catch (error) {

// Code to handle the error

console.error(error.message);

} finally {

// Code that will run regardless of an error occurring

o The finally block is optional and executes after the try and catch blocks.

 Throwing Errors:
o You can create and throw your own errors using the throw statement.

o Example:

javascript

Copy code

function checkValue(value) {

if (value < 0) {

throw new Error("Value must be non-negative");

return value;

4. Asynchronous Error Handling

 Promise Rejection: Use catch() to handle errors in promises.

javascript

Copy code

fetch('some-url')

.then(response => {

if (!response.ok) {

throw new Error('Network response was not ok');

return response.json();

})

.catch(error => console.error('Fetch error:', error));

 Async/Await: Use try...catch within async functions.

javascript

Copy code

async function fetchData() {

try {

const response = await fetch('some-url');

if (!response.ok) throw new Error('Network response was not ok');

const data = await response.json();

return data;
} catch (error) {

console.error('Error fetching data:', error);

5. Best Practices

 Always handle errors to prevent application crashes.

 Log errors to understand what went wrong.

 Provide user-friendly error messages.

 Validate inputs to avoid common errors.

Example Code

Here’s a simple example that incorporates various error handling techniques:

javascript

Copy code

function processInput(input) {

try {

if (typeof input !== 'number') {

throw new TypeError("Input must be a number");

// Simulate an operation that may fail

if (input < 0) {

throw new RangeError("Input must be non-negative");

console.log("Processing input:", input);

} catch (error) {

if (error instanceof TypeError) {

console.error("Type Error:", error.message);

} else if (error instanceof RangeError) {

console.error("Range Error:", error.message);

} else {

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

}
}

// Example usage

processInput(-5); // Logs: Range Error: Input must be non-negative

processInput("test"); // Logs: Type Error: Input must be a number

You might also like