As a web front-end engineer, JavaScript try...catch
is one of our generally used options. In this article, I’ll share 10 try...catch
helpful 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 catch
block . 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 catch
code blocks. For instance, the next block of code will solely catch TypeError
exceptions :
try {
// ...
} catch (error) {
if (error instanceof TypeError) {
// ...
}
}
You may as well use switch
statement 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 Promise
to load sources asynchronously:
try catch (error) {
// ...
}
If an exception happens throughout an asynchronous operation, it’s handed into catch
the code block. Nevertheless, when you do not catch the exception attempt...catch
with <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 lastly
the code block. attempt
The code within the code block lastly
executes 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...catch
Not 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;
}
divide
If b
the worth of is within the operate 0
, an exception is thrown containing the error message. You need to use try...catch
to 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 a
contains b
the 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 throw
the 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 catch
code 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 Promise
using asynchronous code, you should use Promise.catch
the tactic to catch exceptions. For instance:
fetch("/resource")
.then((response) => response.json())
.then((data) => {
// ...
})
.catch((error) => {
// ...
});
On this instance, if fetch
the or json
strategies return exceptions, they’re handed to catch
the tactic for dealing with.
10. Use window.onerror
The final trick is to make use of window.onerror
to catch exceptions globally. window.onerror
Referred to as when an unhandled exception happens within the web page . You possibly can log exception data window.onerror
in 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, handleError
the 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...catch
is 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...catch
and write extra sturdy code.