2017-09-30 3 views
0

page.tsif-elseブロックの外側にあるコードを実行しないようにするにはどうしたらいいですか?

//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:上記のコード断片では、どのように私はライン1、ライン2とライン3の実行を停止しますか?いずれかのtryブロックが例外をキャッチします。

質問2:if-elseステートメントのいずれかで1つのtry-catchブロックしか使用できないのですか?ifまたはelseブロックで例外が検出された場合、1つのtry-catchブロックのみがすべてを処理します。共通コードは行1の行2を実行しません。&行3

+1

私は、ロジックコードが関数内にラップされているものとします。 –

+0

ohhはい、申し訳ありません.. – Aditya

答えて

1

あなたは自動的に、すぐにエラーが発生したとしてcatchブロックにジャンプします両方の条件、arroundのtryブロックを置くことができます。

次の例では、これを実証しようとしています。

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

1

回答1:tryブロックに例外がキャッチされたときの早期復帰。

回答2:tryブロックでif/elseを使用してください。

public someFunction(){ 

    let result; 

    try { 
    result = x ? this.serviceClass.doSomething() : this.serviceClass.doAnotherThing(); 

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

    //other tasks and common functions. //line 3 
    } catch(e) { 

    } 

} 
+0

コンソール文を対応する条件で書くことはできませんか?すなわち 'result = x? 'this.serviceClass.doSomething()'が実行されると、これに対応するコンソールが表示され、もう一方のコンソールも同様に出力されますか?this.serviceClass.doSomething():this.serviceClass.doAnotherThing(); – Aditya

+0

if文が理にかなっているときに、なぜ三項式を推薦していますか?あなたが避けたいものの後ろにcatchステートメントを置くのはなぜですか?最初のエラーがスローされるとすぐに実行を中断してください。 – Mobius

+0

どちらの答えも私のために働きます。自分の要件に最も適したものを考えたいと思います。 – Aditya

関連する問題