What is the advantage of using try {} catch {} versus if {} else {}

前端 未结 14 1473
忘掉有多难
忘掉有多难 2020-11-29 18:19

I am switching from plain mysql in php to PDO and I have noticed that the common way to test for errors is using a try / catch combination instead of if / else combinations.

14条回答
  •  情书的邮戳
    2020-11-29 18:43

    Try and Catch functions are useful whenever there is a communication between functions. In Try and Catch , if there exists an exception in the TRY block, the control is transferred directly to the CATCH block which would store our exception condition. This however is not possible in case of IF ELSE, where in IF condition , if there exists an exception, the control cannot go to the ELSE block howsoever in any case.

    int division(int a,int b){
        if(b==0)
           throw 101;
        return a/b;
    }
    
    int main()
    {
        int a=10,b=0,c;
        try{
            c=division(a,b);
            cout<

    Consider the following Code: throw and catch function is used for communication between functions division and the main function. Note that the statement to print c is not executed when b is 0 as the control directly transfers to the catch block after the value os thrown. This however would not have been possible , had it been IF ELSE here.

提交回复
热议问题