【问题标题】:Is it possible to re-try a try-catch block if error is thrown - JavaScript?如果抛出错误 - JavaScript,是否可以重试 try-catch 块?
【发布时间】:2021-08-27 20:02:21
【问题描述】:

假设我有一个获取随机数的函数,然后返回该数字是否满足条件,如果不满足则抛出错误:

const randFunc = () => {
 let a = Math.floor(Math.random() * 10)
 
 if(a === 5){
     return a
  } else {
     throw new Error('Wrong Num')
 }
}

我想知道的是我是否可以循环这个函数直到我得到'5'

try {
    randFunc()
} catch {
    //if error is caught it re-trys
}

谢谢!

【问题讨论】:

  • 把它放到一个循环中。

标签: javascript function loops error-handling try-catch


【解决方案1】:

只是一个标准的无限循环:

const randFunc = () => {
 let a = Math.floor(Math.random() * 10);
 
 if(a === 5){
     return a;
  } else {
     throw new Error('Wrong Num');
 }
}

function untilSuccess() {
  while (true) {
    try {
      return randFunc();
    } catch {}
  }
}

console.log(untilSuccess());

或递归选项:

const randFunc = () => {
  let a = Math.floor(Math.random() * 10);

  if (a === 5) {
    return a;
  } else {
    throw new Error('Wrong Num');
  }
}

function untilSuccess() {
  try {
    return randFunc();
  } catch {
    return untilSuccess();
  }
}

console.log(untilSuccess());

根据您的重试次数,这可能会破坏您的堆栈(虽然这不是什么大问题)。

【讨论】:

  • 非常感谢,这有助于解决它很高兴知道没有想到 while 循环!
【解决方案2】:

这样的东西可能对你有用

let success = false;
while (!success) {
  try {
    randFunc();
    success = true;
  } catch { }
}

如果 randFunc() 不断抛出,此代码将导致无限循环。

【讨论】:

    【解决方案3】:

    您可以设置recursive function 以继续尝试某些东西,直到它起作用:

    const randFunc = () => {
     let a = Math.floor(Math.random() * 10)
     
     if(a === 5){
         return a
      } else {
         throw new Error('Wrong Num')
     }
    }
    
    getfive()
    
    //getfive is recursive and will call itself until it gets a success
    function getfive(){
      try{
        randFunc()
        console.log('GOT 5!')
      }
      catch(err){
        console.log('DID NOT GET 5')
        getfive()
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2010-09-12
      • 1970-01-01
      • 2023-04-08
      • 2021-03-03
      • 2020-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多