Created
June 26, 2013 01:33
-
-
Save ajmontag/5864052 to your computer and use it in GitHub Desktop.
A sandbox for expirimenting with the throw() declaration. The moral of the story is that the throws() declaration doesn't provide any distinct advantage to programmers or users.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// A sandbox for expirimenting with the throw() declaration | |
// Author: Andrew Montag | |
#include <iostream> | |
#include <stdexcept> | |
class ClassA { | |
public: | |
ClassA(bool throwOnDestruct) : throwOnDestruct_(throwOnDestruct) {} | |
~ClassA() throw () | |
{ | |
if (throwOnDestruct_) { | |
throw std::runtime_error("[ClassA] throwOnDestruct was true"); | |
} | |
} | |
void throwValid() throw (std::runtime_error) { | |
throw std::runtime_error("[ClassA] in throwValid"); | |
} | |
void throwInvalid() throw (std::runtime_error) { | |
throw std::logic_error("[ClassA] in throwInvalid"); | |
} | |
private: | |
const bool throwOnDestruct_; | |
}; | |
void doTestA() | |
{ | |
// This results in: | |
// terminate called after throwing an instance of 'std::runtime_error' | |
// what(): [ClassA] throwOnDestruct was true | |
// Aborted (core dumped) | |
// | |
// ClassA a(true); | |
ClassA a(false); | |
try { | |
a.throwValid(); | |
} catch (const std::runtime_error& e) { | |
std::cout << "1: " << e.what() << std::endl; | |
} | |
// This results in: | |
// terminate called after throwing an instance of 'std::logic_error' | |
// what(): [ClassA] in throwInvalid | |
// Aborted (core dumped) | |
// | |
// try { | |
// a.throwInvalid(); | |
// } catch (const std::runtime_error& e) { | |
// std::cout << "2: " << e.what() << std::endl; | |
// } | |
} | |
int main() | |
{ | |
try { | |
doTestA(); | |
} catch (const std::exception& e) { | |
std::cout << "3: " << e.what() << std::endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment