Does C++ support 'finally' blocks? (And what's this 'RAII' I keep hearing about?)

前端 未结 16 1621
情深已故
情深已故 2020-11-22 17:15

Does C++ support \'finally\' blocks?

What is the RAII idiom?

What is the difference between C++\'s RAII idiom and C#\'s \'using\' statement?

16条回答
  •  盖世英雄少女心
    2020-11-22 17:47

    EDITED

    If you are not breaking/continuing/returning etc., you could just add a catch to any unknown exception and put the always code behind it. That is also when you don't need the exception to be re-thrown.

    try{
       // something that might throw exception
    } catch( ... ){
       // what to do with uknown exception
    }
    
    //final code to be called always,
    //don't forget that it might throw some exception too
    doSomeCleanUp(); 
    

    So what's the problem?

    Normally finally in other programming languages usually runs no matter what(usually meaning regardless of any return, break, continue, ...) except for some sort of system exit() - which differes a lot per programming language - e.g. PHP and Java just exit in that moment, but Python executes finally anyways and then exits.

    But the code I've described above doesn't work that way
    => following code outputs ONLY something wrong!:

    #include 
    #include 
    #include 
    
    std::string test() {
        try{
           // something that might throw exception
           throw "exceptiooon!";
    
           return "fine";
        } catch( ... ){
           return "something wrong!";
        }
        
        return "finally";
    }
    
    int main(void) {
        
        std::cout << test();
        
        
        return 0;
    }
    

提交回复
热议问题