[英]Is it possible to re-try a try-catch block if error is thrown - JavaScript?
假設我有一個 function 獲得一個隨機數,然后返回該數字是否滿足條件,如果不滿足則拋出錯誤:
const randFunc = () => {
let a = Math.floor(Math.random() * 10)
if(a === 5){
return a
} else {
throw new Error('Wrong Num')
}
}
我想知道的是我是否可以循環通過這個 function 直到我得到'5'
try {
randFunc()
} catch {
//if error is caught it re-trys
}
謝謝!
像這樣的東西可能對你有用
let success = false;
while (!success) {
try {
randFunc();
success = true;
} catch { }
}
如果 randFunc() 不斷拋出,此代碼將導致無限循環。
只是一個標准的無限循環:
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());
這可能會破壞您的堆棧,具體取決於您的重試次數(盡管這不是什么大問題)。
您可以設置遞歸 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()
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.