javascript

Error Handling


 

Error handling in JavaScript is essential for writing robust and reliable code. It involves catching and responding to errors that may occur during the execution of your code.

There are various ways to handle errors:

 

1. Try…catch

The try...catch statement is used to manage errors by enclosing code that may throw errors within a try block and providing a mechanism to handle those errors in a catch block.

 

Syntax:

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

 

2. Throw

You can manually throw errors using the throw statement. This is useful for creating custom error conditions or for showing that something unexpected has occurred.

 

Syntax

// throw
throw new Error('Something went wrong');


3. Error Object

JavaScript provides a built-in Error object, which can be used to represent any runtime error.

 

Syntax

// Error object
try {
    if (condition) {
        throw new Error('Custom error message');
    }
} catch (error) {
    console.error(error.message);
}

 

4. Try…catch…finally

The finally block is used to execute code after the try and catch blocks, regardless of whether an error occurred or not.

 

Syntax:

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

 

5. Promise.catch():

When working with promises, you can use the catch() method to handle errors that occur during promise execution.

 

Syntax:

// promise...catch()
myPromiseFunction()
.then(result => {
    // handle success
})
.catch(error => {
    // handle error
});

 

6. Async/await

In Async functions, we can use ‘try…catch’ blocks to handle errors that occur within the asynchronous code.

 

Syntax:

// Async/await
async function myAsyncfunction(){
    try{
        const result = await someAsyncOperation();
        // handle success
    }
    catch(error){
        // handle error
    }
}