In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces "what are the matters needing attention in Try..Catch". In the daily operation, I believe that many people have doubts about the matters needing attention in Try..Catch. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful for you to answer the doubts about "what are the matters needing attention in Try..Catch?" Next, please follow the editor to study!
1. Use try..catch..finally..throw
When dealing with errors in JS, we mainly use the try, catch, finally, and throw keywords.
The try block contains the code we need to check.
The keyword throw is used to throw a custom error
Catch blocks handle captured errors
The finally block is a block that will be executed anyway, and you can do something in this block that needs to be dealt with.
1.1 try
Each try block must be associated with at least one catch or finally block, otherwise a SyntaxError error will be thrown.
We use the try block alone for verification:
Try {throw new Error ('Error while executing the code');} ⓧ Uncaught SyntaxError: Missing catch or finally after try
1.2 try..catch
It is recommended that you use try with catch blocks, which can gracefully handle errors thrown by try blocks.
Try {throw new Error ('Error while executing the code');} catch (err) {console.error (err.message);} ➤ ⓧ Error while executing the code
1.2.1 try..catch and invalid code
Try..catch cannot capture invalid JS code. For example, the following code in the try block is syntactically incorrect, but it is not captured by the catch block.
Try {~! $% ^ & *} catch (err) {console.log ("it will not be executed here");} ➤ ⓧ Uncaught SyntaxError: Invalid or unexpected token
1.2.2 try..catch and Asynchronous Code
Similarly, try..catch cannot catch exceptions thrown in asynchronous code, such as setTimeout:
Try {setTimeout (function () {noSuchVariable; / / undefined variable}, 1000);} catch (err) {console.log ("it will not be executed here");}
Uncaptured ReferenceError will be raised after 1 second:
➤ ⓧ Uncaught ReferenceError: noSuchVariable is not defined
Therefore, we should use try..catch inside the asynchronous code to handle errors:
SetTimeout (function () {try {noSuchVariable;} catch (err) {console.log ("error is caught here!");}}, 1000)
1.2.3 nested try..catch
We can also use nested try and catch blocks to throw errors up, as follows:
Try {try {throw new Error ('Error while executing the inner code');} catch (err) {throw err;}} catch (err) {console.log ("Error caught by outer block:"); console.error (err.message);} Error caught by outer block: ➤ ⓧ Error while executing the code
1.3 try..finally
It is not recommended to use only try..finally without catch blocks, and see what happens below:
Try {throw new Error ('Error while executing the code');} finally {console.log (' finally');} finally ➤ ⓧ Uncaught Error: Error while executing the code
Pay attention to two things here:
Even after an error is thrown from the try block, the finally block is executed
Without catch blocks, errors cannot be handled gracefully, resulting in uncaught errors
1.4 try..catch..finally
It is recommended that you use try...catch blocks and optional finally blocks.
Try {console.log ("Start of try block"); throw new Error ('Error while executing the code'); console.log ("End of try block-- never reached");} catch (err) {console.error (err.message);} finally {console.log (' Finally block always run');} console.log ("Code execution outside try-catch-finally block continue.."); Start of try block ➤ and Error while executing the code Finally block always run Code execution outside try-catch-finally block continue..
There are two more things to pay attention to here:
Subsequent code will not be executed after an error is thrown in the try block
Even after the try block throws an error, the finally block still executes
Finally blocks are typically used to clean up resources or close streams, as follows:
Try {openFile (file); readFile (file);} catch (err) {console.error (err.message);} finally {closeFile (file);}
1.5 throw
The throw statement is used to throw an exception.
Throw / / throw primitives and functions throw "Error404"; throw 42; throw true; throw {toString: function () {return "I'm an object!";}}; / / throw error object throw new Error ('Error while executing the code'); throw new SyntaxError (' Something is wrong with the syntax'); throw new ReferenceError ('Oops..Wrong reference'); / / throw custom error object function ValidationError (message) {this.message = message; this.name =' ValidationError';} throw new ValidationError ('Value too high')
two。 Error handling in Asynchronous Code
Error handling for asynchronous code can be Promise and async await.
2.1 then..catch in Promise
We can use then () and catch () to link multiple Promises to handle the error of a single Promise in the chain, as follows:
Promise.resolve (1) .then (res = > {console.log (res); / / print'1' throw new Error ('something went wrong'); / / throw error return Promise.resolve (2); / / it will not be executed here}) .then (res = > {/ / it will not be executed here either, because the error has not been processed console.log (res) ) .catch (err = > {console.error (err.message); / / print 'something went wrong' return Promise.resolve (3);}) .then (res = > {console.log (res); / / print' 3'}) .catch (err = > {/ / console.error (err) will not be executed here;})
Let's look at a more practical example where we use fetch to call API, which API returns a promise object, and we use catch blocks to handle API failures gracefully.
Function handleErrors (response) {if (! response.ok) {throw Error (response.statusText);} return response;} fetch ("http://httpstat.us/500"). Then (handleErrors). Then (response = > console.log (" ok ")) .catch (error = > console.log (" Caught ", error)); Caught Error: Internal Server Error at handleErrors (: 3:15)
2.2 try..catch and async await
It is easier to use try..catch in async await:
(async function () {try {await fetch ("http://httpstat.us/500");} catch (err) {console.error (err.message);}}) ()
Let's look at the same example where we use fetch to call API, which API returns a promise object, and we use the try..catch block to handle API failures gracefully.
Function handleErrors (response) {if (! response.ok) {throw Error (response.statusText);} (async function () {try {let response = await fetch ("http://httpstat.us/500"); handleErrors (response); let data = await response.json (); return data;} catch (error) {console.log (" Caught ", error)}}) () Caught Error: Internal Server Error at handleErrors (: 3:15) at: 11:7
3. Built-in errors in JS
3.1 Error
JavaScript has a built-in error object, which is usually thrown by the try block and captured in the catch block, and the Error object contains the following attributes:
Name: is the wrong name, such as "Error", "SyntaxError", "ReferenceError", etc.
Message: messages about error details.
Stack: is a stack trace of errors for debugging purposes.
We create an Error object and look at its name and message properties:
Const err = new Error ('Error while executing the code'); console.log ("name:", err.name); console.log ("message:", err.message); console.log ("stack:", err.stack); name: Error message: Error while executing the code stack: Error: Error while executing the code at: 1:13
JavaScript has the following built-in errors, which are inherited from the Error object
3.2 EvalError
EvalError indicates an error about the global eval () function, which is no longer thrown by JS, but exists for backward compatibility.
3.3 RangeError
RangeError is thrown when the value is out of range.
➤ [] .length =-1 ⓧ Uncaught RangeError: Invalid array length
3.4 ReferenceError
ReferenceError is thrown when a variable that does not exist is referenced.
➤ x = x + 1; ⓧ Uncaught ReferenceError: x is not defined
3.5 SyntaxError
SyntaxError is thrown when you use any incorrect syntax in your JS code.
➤ function () {return 'hight'} ⓧ Uncaught SyntaxError: Function statements require a function name ➤ 1 = 1 ⓧ Uncaught SyntaxError: Invalid left-hand side in assignment ➤ JSON.parse ("{x}"); ⓧ Uncaught SyntaxError: Unexpected token x in JSON at position 2
3.6 TypeError
If the value is not of the expected type, TypeError is thrown.
➤ 1 (); ⓧ Uncaught TypeError: 1 is not a function ➤ null.name; ⓧ Uncaught TypeError: Cannot read property 'name' of null
3.7 URIError
If the global URI method is used in the wrong way, URIError is thrown.
➤ decodeURI ("%%"); ⓧ Uncaught URIError: URI malformed
4. Define and throw custom errors we can also define custom errors in this way.
Class CustomError extends Error {constructor (message) {super (message); this.name = "CustomError";}}; const err = new CustomError ('Custom error while executing the code'); console.log ("name:", err.name); console.log ("message:", err.message); name: CustomError message: Custom error while executing the code
We can also further enhance the CustomError object to contain the error code
Class CustomError extends Error {constructor (message, code) {super (message); this.name = "CustomError"; this.code = code;}}; const err = new CustomError ('Custom error while executing the code', "ERROR_CODE"); console.log ("name:", err.name); console.log ("message:", err.message); console.log ("code:", err.code); name: CustomError message: Custom error while executing the code code: ERROR_CODE
Use it in try..catch blocks:
Try {try {null.name;} catch (err) {throw new CustomError (err.message, err.name); / / message, code}} catch (err) {console.log (err.name, err.code, err.message);} at this point, the study of "what are the matters needing attention for Try..Catch" is over, hoping to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.