preface
I finally have time to update my blog this weekend. First of all, I would like to thank “JustJavac” for writing an objection to my article “Try Catch With Caution”. I learned a lot about it (such as Chrome’s Pause on Exceptions feature). It also made me realize that some knowledge points are not deep enough and there are not enough references. However, some words of “JustJavac” are quite extreme, which can easily lead readers to mislead my thoughts, and also lead to some knowledge directly out of context and over-generalization (for example, try catch does not need to worry about performance problems at all). So I decided to revise this blog, hoping to show you the most accurate dry goods, welcome you to comment.
Since version 3 of ECMA-262, the try catch statement was introduced as a standard way of handling exceptions in JavaScript. The basic syntax is shown below.
Basic syntax for try catch
try {
// Code that may cause errors
} catch (error) {
// What happens when an error occurs
}finally {
// Execute even if an error is reported
}
Copy the code
2, try catch characteristics
1. Try catch consumes performance
1.1 Try catch performance
ECMAScript 2015 -The try Statement
13.15.5 Static Semantics: VarDeclaredNames
- TryStatement : try Block Catch Finally
- 1.Let names be VarDeclaredNames of Block.
- 2.Append to names the elements of the VarDeclaredNames of Catch.
- 3.Append to names the elements of the VarDeclaredNames of Finally.
- 4.Return names.
13.15.6 Static Semantics: VarScopedDeclarations
- TryStatement : try Block Catch Finally
- 1.Let declarations be VarScopedDeclarations of Block.
- 2.Append to declarations the elements of the VarScopedDeclarations of Catch.
- 3.Append to declarations the elements of the VarScopedDeclarations of Finally.
- 4.Return declarations.
According to the above ECMAScript documentation 13.15.5 and 13.15.6 ‘.
The following is only for this girl’s own translation understanding, for reference only
To run a try catch, you need to add the current lexical environment and scope to the block of code that the catch and Finally, respectively, will execute. We can infer from the above that try catches are performance consuming.
1.2 Try catch performance experiment
Below I use Chrome62 and IE9 respectively to add a number of try catch, comparative experiment, although, very want to abandon the evil IE, but many domestic products do not allow ah, unless we go to the gym to practice more, fight a fight, hey hey ~ ~ 1.2.1 experimental data:
// Do not add try catch
(function () {
var i = 0; i++; } ())Copy the code
/ / have a try to catch
(function () {
var i = 0;
try {
i++;
} catch (ex) {
} finally{}} ())Copy the code
1.2.2 Experimental results:
1.2.3 Experiment Link:
Jsperf.com/test-try-ca…
Jsperf.com/test-try-ca…
If you’re looking at the new TurboFan compiler for the V8 engine, check out v8_8h_source at line 3354. But IE11 is slower. Depending on your partner’s business object, try catches have little impact on performance if they are only available to modern browsers; If you need to be compatible with IE or embedded in low-end WebViews, try catch consumption can be considered appropriately.
2. Try catch failed to catch an asynchronous error
A try catch operation on an asynchronous method will only catch exceptions in the event loop, not those thrown in the callback.
try {
setTimeout((a)= >{
const A = 1
A = 2
},0)}catch (err) {
// There is no way to catch an exception thrown by a callback
console.log("-----catch error------")
console.log(err)
}
Copy the code
In the case of asynchrony, if you want to catch an exception, it is recommended to wrap a try catch layer in the asynchrony function.
setTimeout((a)= > {
try {
const A = 1
A = 2
} catch (err) {
console.log(err)
}
}, 0)
Copy the code
3. Try catch to throw an error
The try-catch statement is accompanied by the throw operator, which throws a defined error at any time. You can create custom error messages based on different error types.
throw new Error("Something bad happened.");
throw new SyntaxError("I don’t like your syntax.");
throw new TypeError("What type of variable do you take me for?"); throw new RangeError("Sorry, you just don’t have the range.");
throw new EvalError("That doesn 't the evaluate.");
throw new URIError("Uri, is that you?");
throw new ReferenceError("You didn’t cite your references properly.");
Copy the code
If you feel that custom errors are not appropriate and want to see native errors, you can use Chrome’s Pause on Exceptions function
Try to catch STH
Try catches are best for handling errors that we have no control over, such as I/O operations. Back-end nodeJs or Java read I/O operations, such as database reading, so try catches are used more often. The front end can be used for uploading images, reporting errors with other people’s JS libraries, synchronizing async await interfaces, etc.
async function f() {
try {
await Promise.reject('Something went wrong');
} catch(e) {
}
return await Promise.resolve('hello world');
}
Copy the code
But most front-end client code: no processing is dependent on the environment nor I/O operations, are writing your own code, in know your code will plainly when an error occurs, then use the try catch statement is not appropriate, the corresponding data types of errors, suggest friends use deconstruction assignment specify a default value, &&, | | to evade, So be careful with try catch.
foo = (obj = {}) = > {
let obj1 = result || {};
if (obj && obj.code) {
console.log('obj.code',obj.code)
}
}
Copy the code
The resources
- Raoenhui. Making. IO/js / 2018/12 /…
- ECMAScript 2015 -The try Statement
- Developers.google.com/web/updates…
- V8docs.nodesource.com/node-0.8/d4…
Happy coding .. 🙂