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

前端 未结 14 1429
忘掉有多难
忘掉有多难 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:42

    TRY/ CATCH can be used within the programming context where you have very little information about the error or you think that might can occur such as.

    #include 
    using namespace std;
    
    int main (){
        try{
            while(true){
                new int[100000];
            }
        }
        catch(bad_alloc& e){
           cout << e.what() << endl;
         }
     }
    

    Although there are no semantic or compile-time errors in the program, but it's understandable that it posses a run-time error which is "bad_alloc" which appears when you try to continuously allocate the memory and your program run out of memory. This exception is defined in bad_alloc standard class which is a child-class of class "Exception", since it throws an implicit exception, throw keyword is not implied here.

    You can also use try/catch to check if the file is accidentally deleted and can use if/else to check if there exists a file or not, both have their own advantages.

提交回复
热议问题