gpt4 book ai didi

javascript - 如何防止在 if-else block 之外执行命令代码?

转载 作者:行者123 更新时间:2023-12-01 02:59:51 26 4
gpt4 key购买 nike

page.ts

//all imports are made correctly

export class page{

constructor(){}//used DI correctly.

public someFunction(){

let result: any;


if(x = true){
try{
result = this.serviceClass.doSomething();
}
catch(e){
//do some processing.
}
}
else{
try {
result = this.serviceClass.doAnotherThing();
}
catch(e){
//do some processing.
}
}

console.log(result); //line 1
service2.oneThing(); ///line 2

//other tasks and common functions. //line 3
}
}

问题1:在上面的代码中,如何停止第1行、第2行和第3行的执行?当任何一个 try block 捕获异常时。

问题2:如何在两个 if - else 语句中只使用一个 try-catch block ?也就是说,如果在 if 或 else block 中捕获到任何异常,则仅使用一个 try-catch block 执行所有操作,并且公共(public)代码不会执行,即第 1 行、第 2 行和第 3 行。

最佳答案

您可以将两个条件放在 try block 中,一旦发生错误,它就会自动跳转到 catch block 。

在下面的示例中,我尝试演示这一点。

function getResult1(shouldThrow){
if (shouldThrow) throw new Error("FAILED TO GET RESULT 1");
return 1;
}

function getResult2(shouldThrow){
if (shouldThrow) throw new Error("FAILED TO GET RESULT 2");
return 2;
}

function doIt(condition, shouldThrow){
var result;
try {
if (condition){
result = getResult1(shouldThrow);
} else {
result = getResult2(shouldThrow);
}

console.log("Successfully got result", result);

} catch (e) {
console.error('We ran into an error', e.toString());
}
}


for(var i = 0; i < 4; i++){
var shouldThrow = i % 2 == 0;
var condition = i > 2;
console.log(`Trying condition = ${condition} and shouldThrow = ${shouldThrow}`);
doIt(condition, shouldThrow);
console.log("------------------");
}

关于javascript - 如何防止在 if-else block 之外执行命令代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46504539/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com