[JS basics] try catch usage

try catch usage

What is the try...catch statement?

try...catch can test for errors in the code. The try part contains the code that needs to be run, and the catch part contains the code that runs when the error occurs

try...catch syntax

try {
    
    
    // 在此运行代码
} catch(err) {
    
    
    // 在此处理错误
}

运行流程:
try{
    
    ...}包含块中的代码有错误,则运行catch(err){
    
    ...}内的代码,否则不运行catch(err){
    
    ...}内的代码

try...catch case

var array = null;
try {
    
    
    document.write(array[0])
} catch(err) {
    
    
    document.writeln('error name' + err.name + '');
    document.writeln('error message: ' + err.message);
}

Insert picture description here

try...catch...finally syntax

try {
    
    
    tryStatements
} catch(exception) {
    
    
    catchStatements
} finally {
    
    
    finallyStatements
}

参数
   tryStatements: 必选项,可能发生错误的语句
   exception: 必选项,任何变量名 exception 的初始化值是扔出的错误的值
   catchStatements 可选项,处理在相关联的 tryStatement 中发生的错误的语句
   finallyStatements: 可选项,在所有其他过程发生之后无条件执行的语句

try...catch...finally case

var array = null;
try {
    
    
    document.write(array[0])
} catch(err) {
    
    
    document.writeln('error name: ' + err.name + '' )
    document.writeln('error message: ' + err.message)
}
finally{
    
    
    alert('object is null');
}

程序执行过程
    1.array[0]的时候由于没有创建array数组,array是个空对象,程序中调用array[0]就会产生object is null 的异常
    2.catch(err)语句捕获到这个异常通过err.name打印了错误类型,err.message打印了错误的详细信息
    3.finally类似与java的finally,无论有无异常都会执行

Now summarize the information corresponding to the six values ​​of Error.name:

  1. EvalError: The use of eval() is inconsistent with the definition
  2. RangeError: Value is out of range
  3. ReferenceError: illegal or unrecognized reference value
  4. SyntaxError: A syntax analysis error occurred
  5. TypeError: The operand type is wrong
  6. URIError: Improper use of URI processing function

Guess you like

Origin blog.csdn.net/weixin_43352901/article/details/108527240