JS uses a try catch to catch an exception
The blog instructions
The information involved in the article comes from the Internet and personal summary, meaning lies in personal learning and experience summary, if there is any infringement, please contact me to delete, thank you!
Introduction to the
The front end is at the forefront of customer penetration, with special attention to user experience. During development, the occurrence of exceptions cannot be controlled due to various problems. Therefore, exceptions need to be handled to optimize user experience.
Try catch finally
The **try** statement allows you to define a block of code for error testing at execution time.
The catch statement allows you to define which block of code to execute when an error occurs with the try block.
Finally statements are executed after a try and catch with or without exceptions.
Note: Both catch and finally statements are optional, but at least one must be used when using a try statement. When an error occurs, JavaScript stops execution and generates an error message. You can use the throw statement to create a custom message (throwing an exception)
try {
// tryCode - Try to execute a block of code
}
catch(err) {
// catchCode - catch the error code block
}
finally {
// finallyCode - a block of code that executes regardless of the result of the try/catch
}
Copy the code
The need for exception handling
Enhanced user experience, accurate problem location, and improved front-end solutions, such as front-end monitoring systems
Exception handling scenarios
JS syntax error, code exception
Abnormal Promise
The Iframe abnormal
Cross-domain abnormal
The interface failed to request an AJAX request. Procedure
The static resource import fails to be loaded
Try catch
Only synchronous exceptions can be caught, but syntax and asynchronous exceptions cannot be caught. Therefore, you need to pay attention to them in daily use
// Failed to catch syntax exceptions
try {
let name = 'aaa // write less '
} catch(e) {
console.log('Exception caught:',e);
}
// VM421:1 Uncaught SyntaxError: Unexpected identifier
// Cannot catch asynchronous exceptions
try {
setTimeout(() = > {
console.log(a) // The variable a is not declared
}, 1000)}catch(e) {
console.log('Exception caught:',e);
}
// blog.js:1 Uncaught ReferenceError: a is not defined
Copy the code
Thank you
Universal network
Novice tutorial
Es6 grammar tutorial by Yifeng Ruan
And hard-working self, personal blog, GitHub