js中-异常的处理方式(Error) 和捕获异常(try/catch)

函数出现错误处理

throw 关键字,抛出一个异常信息

function sum(num1, num2) {
  // 当传入的参数的类型不正确时,应该告知调用者一个错误
  if (typeof num1 !== 'number' || typeof num2 !== 'number') {
    throw '抛出一个错误'
  }
  // return num1 + num2
}

// 调用者(如果没有对错误进行处理,那么程序会直接终止)
console.log(sum({ name: 'coder' }, true));

抛出异常的其他补充

class HError {
  constructor(type, message) {
    this.type = type
    this.message = message
  }
}

function foo(type) {
  console.log('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')
    // console.log(err.name);
    // console.log(err.stack);
    // console.log(err.message);
    // throw err

    // 5. Error的子类
    // throw new RangeError('下标值越界时使用的错误类型')
    // throw new SyntaxError('解析语法错误时使用的错误类型')
    throw new TypeError('出现类型错误时,使用的错误类型')

    // 强调: 如果函数中已经抛出了异常,那么后续的代码都不会继续执行了
  }
  console.log('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) {
    // 这里做捕获到错误时,做的操作
    console.log(error.message);
    bar(1)
  } finally {
    // console.log('这里不管有没有错误,一定会执行的');
  }
  console.log('bar函数后面的代码');
}

test()
console.log('执行完毕');

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

派大星965

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值