JavaScript Error Handling

try-catch

try-catch blocks are the most basic structures used for error handling in JavaScript.

                    try {
                        // code that may throw an error
                    } catch (error) {
                        // handle the error
                    }
                

Asynchronous Operations

Example: Promise with try-catch

function fetchData() {
        return new Promise((resolve, reject) => {
            try {
                // Simulate an API call
                setTimeout(() => {
                    const data = { id: 1, name: 'John Doe' };
                    resolve(data);
                }, 1000);
            } catch (error) {
                reject(error);
            }
        });
    }

Example: async/await with try-catch

async function fetchData() {
        try {
            const response = await fetch('https://api.example.com/data');
            const data = await response.json();
            console.log(data);
        } catch (error) {
            console.error('Error:', error);
        }
    }