realjema

10 try…catch Functions in JS

As a web front-end engineer, JavaScript try...catchis one of our generally used options. In this article, I’ll share 10 try...catchhelpful tips to make you extra comfy when dealing with exceptions.

1. Catch all exceptions

If you wish to catch all potential exceptions in your code, you should use a catchblock . For instance:

try {
// ...
} catch {
// ...
}

This methodology will catch all exceptions, together with “syntax errors” , “runtime errors” and “customized errors” . Nevertheless, when utilized in a production environment, it is suggested to be specific in regards to the exception types to catch for better problem diagnosis.

2. Catching particular kinds of exceptions

In the event you solely wish to catch certain kinds of exceptions, you should use conditional statements inside catchcode blocks. For instance, the next block of code will solely catch TypeErrorexceptions :

try {
// ...
} catch (error) {
if (error instanceof TypeError) {
// ...
}
}

You may as well use switchstatement to examine the exception type:

try {
// ...
} catch (error) {
switch (error.constructor) {
case TypeError:
// ...
break;
case RangeError:
// ...
break;
// ...
}
}

3. Catching asynchronous exceptions

In the event you use asynchronous code, chances are you’ll must catch exceptions in asynchronous code. For instance, the next code block makes use of Promiseto load sources asynchronously:

try  catch (error) {
// ...
}

If an exception happens throughout an asynchronous operation, it’s handed into catchthe code block. Nevertheless, when you do not catch the exception attempt...catchwith <i>, will probably be handled as an unhandled exception.

4. Clean up resources within the finally code block

In the event you use some sources that must be cleaned up manually (resembling file handles or community connections), you possibly can carry out cleanup operations in lastlythe code block. attemptThe code within the code block lastlyexecutes no matter whether or not an exception happens within the code block. For instance:

let resource;
try
resource = acquireResource();
// ...
catch (error) {
// ...
} finally
releaseResource(resource);

5. Throw an exception

try...catchNot only can exceptions be caught, however exceptions may also be thrown. You possibly can manually throw exceptions in your code utilizing throw statement . For instance:

function divide(a, b) {
if (b === 0) {
throw new Error("error");
}
return a / b;
}

divideIf bthe worth of is within the operate 0, an exception is thrown containing the error message. You need to use try...catchto catch this exception and take appropriate action.

6. Pass additional information in the exception

When an exception is thrown, you possibly can go some extra data to assist debug the issue. For instance:

function divide(a, b) {
if (b === 0) {
throw new Error("error", { a, b });
}
return a / b;
}

In this instance, the exception object acontains bthe values ​​of and when the divisor is zero. While you catch this exception, you possibly can access the values ​​and act accordingly.

7. Rethrow the exception

Typically, when dealing with an exception, you must rethrow the exception so that higher-level code can deal with it. You need to use throwthe statement to rethrow an exception. For instance:

try {
// ...
} catch (error) {
// ...
throw error;
}

On this instance, the exception is rethrown and handed to the calling operate for dealing with.

8. Catch errors and ignore them

Typically, whereas debugging your code, chances are you’ll want to quickly ignore some errors. You need to use empty catchcode blocks to disregard exceptions. For instance:

try {
// ...
} catch {
// ...
}

Nevertheless, it’s not really helpful to make use of this methodology in a manufacturing surroundings. Ignoring exceptions in a manufacturing surroundings can result in unpredictable habits of your code.

9. Using the Promise.catch methodology

If you Promiseusing asynchronous code, you should use Promise.catchthe tactic to catch exceptions. For instance:

fetch("/resource")
.then((response) => response.json())
.then((data) => {
// ...
})
.catch((error) => {
// ...
});

On this instance, if fetchthe or jsonstrategies return exceptions, they’re handed to catchthe tactic for dealing with.

10. Use window.onerror

The final trick is to make use of window.onerrorto catch exceptions globally. window.onerrorReferred to as when an unhandled exception happens within the web page . You possibly can log exception data window.onerrorin to facilitate prognosis of issues in a manufacturing surroundings. For instance:

window.onerror = function handleError(message, source, lineno, colno, error) {
// ...
};

On this instance, when an exception happens within the web page, handleErrorthe operate might be known as and the exception data might be handed as a parameter. You possibly can log exception data on this operate and ship it to the server for straightforward evaluation.

in conclusion

In JavaScript, try...catchis a robust exception dealing with device. It may possibly assist you diagnose and debug issues in your code and be certain that your code handles distinctive circumstances at runtime. By mastering these 10 utilization ideas, you possibly can higher use attempt...catchand write extra sturdy code.

realjema

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments

Follow us

Don't be shy, get in touch. We love meeting interesting people and making new friends.

Most popular

Most discussed