Skip to content

Instantly share code, notes, and snippets.

@mido3ds
Created May 29, 2017 11:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mido3ds/35c61d160fc2db4838d3b455d427c091 to your computer and use it in GitHub Desktop.
Save mido3ds/35c61d160fc2db4838d3b455d427c091 to your computer and use it in GitHub Desktop.
c++ rethrow cases
#include <iostream>
using namespace std;
class except1 {};
class except2 {};
void someFunction() {
try {
throw except1();
} catch(const except1& e) {
cout << "catched at someFunction\n";
cout << "rethrowing\n";
throw except2(); // this will be catched at main not here
} catch(const except2& e2) {
cout << "this wont be printed\n";
}
}
int main(int argc, char* argv[]) {
try {
someFunction();
} catch(const except2& e) {
cout << "catched at main\n";
}
}
/*output:
catched at someFunction
rethrowing
catched at main
*/
#include <iostream>
using namespace std;
class except1 {};
class except2 {};
void someFunction() {
try {
throw except1();
} catch(const except1& e) {
cout << "catched at someFunction\n";
cout << "rethrowing\n";
throw except2(); // this will crash the program, as previous function (main) dont catch it
} catch(const except2& e2) {
cout << "this wont be printed\n";
}
}
int main(int argc, char* argv[]) {
someFunction();
}
/*output:
catched at someFunction
rethrowing
libc++abi.dylib: terminating with uncaught exception of type except2
Abort trap: 6
*/
#include <iostream>
using namespace std;
class except1 {};
class except2 {};
void someFunction() {
try {
throw except1();
} catch(const except1& e) {
cout << "catched at someFunction\n";
cout << "rethrowing\n";
try {
throw except2(); // we will rethrow it and catch it in the same catch, it wond rewind the stack, it will be catched here
} catch (const except2& e2) {
cout << "catched except2 after rethrowing it\n";
}
cout << "this will be printed after continuing the above handling\n";
} catch (const except2& e2) {
cout << "this wont be printed, as it is handled above\n";
}
cout << "no problem at all , all errors have been handled, even if there was a rethrow\n";
}
int main(int argc, char* argv[]) {
try {
someFunction();
} catch (const except2& e) {
cout << "this wont be printed, as this exception has been handled in someFunction\n";
}
}
/*output:
catched at someFunction
rethrowing
catched except2 after rethrowing it
this will be printed after continuing the above handling
no problem at all , all errors have been handled, even if there was a rethrow
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment