繁体   English   中英

如何在 Typescript 中使用 Try and Catch

[英]How to use Try and Catch with Typescript

我想当函数 sum 的两个参数是数字时,代码成功,但是当两个参数之一不是数字时,我想抛出异常。

  const sum = (num1: number, num2: number) => {
    return num1 + num2;
  };

  try {
    typeof sum(8, 'A') === 'number';
  } catch (e) {
    console.log('the type you entered is NaN');
  }

现在作为测试,我输入了一个字符串值而不是 num2 但代码运行时没有在控制台中显示异常我的意思是它没有从 catch 块中记录“您输入的类型是 NaN”

catch (e) {
    console.log('the type you entered is NaN');
  }

当参数不是数字时,我想在控制台中记录它,如何做到这一点?

Typescript 不会在运行时抛出异常,它会编译成原生 javascript。 它只能显示您的类型错误并在编译期间抛出错误。 如果要捕获异常,可以使用throw new Error('/*error text*/')

只是抛出一个新错误:

  const sum = (num1: number, num2: number) => {
    return num1 + num2;
  };

  try {
    if (typeof sum(8, 'A') !== 'number'){
      throw new Error('the type you entered is NaN')
    }
  } catch (e) {
    console.log(e);
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM