Quantcast
Channel: Does C++ support 'finally' blocks? (And what's this 'RAII' I keep hearing about?) - Stack Overflow
Viewing all articles
Browse latest Browse all 17

Answer by jave.web for Does C++ support 'finally' blocks? (And what's this 'RAII' I keep hearing about?)

$
0
0

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 toodoSomeCleanUp(); 

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 ONLYsomething wrong!:

#include <stdio.h>#include <iostream>#include <string>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;}

Viewing all articles
Browse latest Browse all 17

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>