When we use JavaScript for program development, we inevitably encounter a variety of errors: variable undefined, null value access, attribute not present, etc. because JavaScript is interpreted, there are some spelling mistakes that are more unlikely to be found before running, So how do you deal with so many kinds of javascript errors?
When an error occurs, the JavaScript engine stops and throws an error that contains an error message. In JavaScript, we can use Try...catch ... Statement to capture these error messages.
Try...catch ... Statement
The try statement allows us to define a block of code that performs error testing at execution time.
The catch statement allows us to define a block of code that executes when a try block of code has an error.
The try and catch in JavaScript are paired, otherwise they will cause a syntax error!
Grammar
Try { // Run code here }catch (err) { /// Handling Errors Here }
In the following example, we deliberately write an undefined function in the code of the try block, the catch block catches the error in the try block, and executes the code to handle it.
<!DOCTYPE HTML><HTML><Head> <Script> vartxt= ""; functionmessage () {Try{showmessage ("Hi there!"); } Catch(err) {txt= "An error has occurred \ nyou"; TXT+= "Error Description:" +Err.message+ "\ n"; alert (TXT); } } </Script></Head><Body> <inputtype= "button"value= "View message"onclick= "message ()"></Body></HTML>
JavaScript Try...catch ... Statement