持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第26天,点击查看活动详情
这篇文章给0基础的人看的。其他人免得浪费时间绕过。
翻译自github的一个专栏
Error Handling
JavaScript是弱类型语言。有时候当我们访问的变量为undefined 或者调用的方法未undefined未定义的时候,将会抛出运行时异常 JavaScript提供了类似于Python或者Java那样的错误处理机制,可以使用Try-Catch-Finally 代码块来捕获运行时错误。
try {
// code that may throw an error
} catch (err) {
// code to be executed if an error occurs
} finally {
// code to be executed regardless of an error occurs or not
}
try: 用try包裹可能抛出异常的代码块,try在执行中测试可能抛出的错误。
catch: catch是在try代码块中执行抛出错误时,执行catch包裹的代码块,cache方法会返回一个包含错误信息的参数error,catche通常用来打印错误日志,或者展示错误信息给用户
finally: finally 代码块通常无论try中的代码执行错误,还是正常,都会执行。 所以finally通常用于完善剩余任务或者重置一些因为在cache中变化的变量。
例如:
try {
let lastName = 'Yetayeh'
let fullName = fistName + ' ' + lastName
} catch (err) {
console.log(err)
}
ReferenceError: fistName is not defined
at <anonymous>:4:20
try {
let lastName = 'Yetayeh'
let fullName = fistName + ' ' + lastName
} catch (err) {
console.error(err) // we can use console.log() or console.error()
} finally {
console.log('In any case I will be executed')
}
ReferenceError: fistName is not defined
at <anonymous>:4:20
In any case it will be executed
catch代码块接受一个参数,通常取名为e,err,error。它是一个包含name, message等key的对象
try {
let lastName = 'Yetayeh'
let fullName = fistName + ' ' + lastName
} catch (err) {
console.log('Name of the error', err.name)
console.log('Error message', err.message)
} finally {
console.log('In any case I will be executed')
}
Name of the error ReferenceError
Error message fistName is not defined
In any case I will be executed
throw: throw语句允许我们创建自定义错误,我们可以抛出 string, number, boolean 或者对象 使用throw语句抛出异常,表达式指定异常的值。以下每种情况都会引发异常
throw 'Error2' // 抛出一个string类型的错误信息
throw 42 // 抛出一个number类型的错误信息
throw true // bool
throw new Error('Required') // Error对象
const throwErrorExampleFun = () => {
let message
let x = prompt('Enter a number: ')
try {
if (x == '') throw 'empty'
if (isNaN(x)) throw 'not a number'
x = Number(x)
if (x < 5) throw 'too low'
if (x > 10) throw 'too high'
} catch (err) {
console.log(err)
}
}
throwErrorExampleFun()
Error Types
- ReferenceError:发生非法引用异常。如果使用尚未声明的变量,将引发ReferenceError
let firstName = 'Asabeneh'
let fullName = firstName + ' ' + lastName
console.log(fullName)
Uncaught ReferenceError: lastName is not defined
at <anonymous>:2:35
- SyntaxError: 语法错误
let square = 2 x 2 // 看了好久原来是把字母X当成*用的
console.log(square)
console.log('Hello, world")
Uncaught SyntaxError: Unexpected identifier
- TypeError: 类型错误
let num = 10
console.log(num.toLowerCase())
Uncaught TypeError: num.toLowerCase is not a function
at <anonymous>:2:17
这些是您编写代码时可能会遇到的一些常见错误。了解错误可以帮助您知道自己犯了什么错误,这将帮助您快速调试代码。