函数出现错误处理
throw 关键字,抛出一个异常信息
function sum(num1, num2) {
// 当传入的参数的类型不正确时,应该告知调用者一个错误
if (typeof num1 !== 'number' || typeof num2 !== 'number') {
throw '抛出一个错误'
}
// return num1 + num2
}
// 调用者(如果没有对错误进行处理,那么程序会直接终止)
(sum({ name: 'coder' }, true));
抛出异常的其他补充
class HError {
constructor(type, message) {
= type
= message
}
}
function foo(type) {
('foo函数的开始执行');
if (type === 0) {
// 1.抛出一个字符串类型(基本的数据类型)
// throw 'error'
// 2.比较常见的是抛出一个对象类型
// throw {
// errorCode: -1001,
// errorMessage: 'type不能为0'
// }
// 3.创建类, 并且创建这个类对应的对象
// throw new HError(1001, 'type不能为0')
// 4.提供了一个Error
// const err = new Error('type不能为0')
// ();
// ();
// ();
// throw err
// 5. Error的子类
// throw new RangeError('下标值越界时使用的错误类型')
// throw new SyntaxError('解析语法错误时使用的错误类型')
throw new TypeError('出现类型错误时,使用的错误类型')
// 强调: 如果函数中已经抛出了异常,那么后续的代码都不会继续执行了
}
('foo函数的结束执行');
}
foo(0)
对抛出的异常进行处理
function foo(type) {
if (type === 0) {
throw new Error('foo error message~')
}
}
// 1. 第一种是不处理,bar函数会继续将收到的异常直接抛出去
function bar(type) {
foo(type)
}
// 2.第二种try/catch 捕获异常
function test() {
try {
// 如果bar函数有异常,程序不会终止,错误信息会到catch里捕获
bar(0)
} catch (error) {
// 这里做捕获到错误时,做的操作
();
bar(1)
} finally {
// ('这里不管有没有错误,一定会执行的');
}
('bar函数后面的代码');
}
test()
('执行完毕');