JavaScript Errors - throw, try, and catch
JavaScript Errors - throw, try, and catch
try statements test blocks of code for errors.
catch statement handles errors.
throw statement creates a custom error.
JavaScript Errors
When the JavaScript engine executes JavaScript code, various errors may occur.
may be a syntax error, usually a coding error or typo made by the programmer.
could be a spelling mistake or a missing feature in the language (possibly due to browser differences).
The error may be caused by incorrect output from the server or user.
Of course, it may also be due to many other unpredictable factors.
JavaScript throws errors
When an error occurs, when something goes wrong, the JavaScript engine usually stops and generates an error message.
The technical term to describe this situation is: JavaScript will throw an error.
JavaScript try and catch
try statements allow us to define blocks of code that are tested for errors when executed.
The catch statement allows us to define the code block that is executed when an error occurs in the try code block.
JavaScript statements try and catch appear in pairs.
Syntax
try { //在这里运行代码 }catch(err){ //在这里处理错误}
Examples
In the following example, we intentionally wrote a typo in the code of the try block.
The catch block catches the error in the try block and executes code to handle it.
var txt=""; function message(){ try { adddlert("Welcome guest!"); } catch(err) { txt="本页有一个错误。\n\n"; txt+="错误描述:" + err.message + "\n\n"; txt+="点击确定继续。\n\n"; alert(txt); } }