Aditya Aditya - 1 year ago 92
Javascript Question

How can I prevent executing comman code outside if-else block?

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
}
}


Question1: In the above piece of code, How do I stop the execution of line 1, line 2 and line 3? When any of the try block catches the exception.

Question2: How can I use only one try-catch block for both if - else statements?That is if any exception is caught either in if or in else block only one try-catch block will do everything, and the common code does not execute i.e line 1 line 2 & line 3.

Answer Source

You can put the try block arround both conditions, which will automatically jump to the catch block as soon as an error occurs.

In the following example I try to demonstrate this.

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("------------------");
}

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download