try catch finally何时使用
1.try里面的代码报错的时候,catch里面的代码才会执行,finally里面的代码永远会执行
2.try里面的一行代码出错,try代码块里错误代码之后的代码不会走到
3.catch代码块里有错误代码会报错,并且错误代码之后的代码不会走到, finally同理
4.如果只是catch里面代码出错,则报catch里面的错误
5.如果catch和finally都出错则会报finally里面的错误
try {
console.log(111)
} catch (e) {
console.log(222)
} finally {
console.log(333)
}
情况1结果:111 333
try {
consol2e.log('aa')
console.log(111)
} catch (e) {
console.log(222)
} finally {
console.log(333)
}
情况2结果:222 333
try {
consol2e.log('aa')
console.log(111)
} catch (e) {
console.log(222)
consolew.log('catch error')
conmsole.log('错误代码之后的一句')
} finally {
console.log(333)
}
情况3 4结果:222
333
/Users/yangming/mycode/test/vue/util.js:71
consolew.log('catch error')
^
ReferenceError: consolew is not defined
at Object.<anonymous> (/Users/yangming/mycode/test/vue/util.js:71:5)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
at startup (internal/bootstrap/node.js:236:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:560:3)
try {
consol2e.log('aa')
console.log(111)
} catch (e) {
console.log(222)
consolew.log('catch error')
conmsole.log('错误代码之后的一句')
} finally {
console.log(333)
consol1e.log(333)
conmsole.log('finally错误代码之后的一句')
}
情况5结果
222
333
/Users/yangming/mycode/test/vue/util.js:75
consol1e.log(333)
^
ReferenceError: consol1e is not defined
at Object.<anonymous> (/Users/yangming/mycode/test/vue/util.js:75:5)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
at startup (internal/bootstrap/node.js:236:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:560:3)