Last active
August 29, 2015 14:10
-
-
Save andreasgrv/02c025f27da254d2a854 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| exception_game | |
| ============== | |
| How 'not' to use exception handling. | |
| Well since C++ unlike Java actually lets the programmer figure out how he wants to use exceptions.. | |
| Why not exploit the exceptions mechanism and be a bit more creative!? |
This file contains hidden or 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
| #include <iostream> | |
| #include <unistd.h> | |
| #include <random> | |
| using namespace std; | |
| void cplusplus(int); | |
| void player(int); | |
| static mt19937_64 rng; // random number generator | |
| const int num = 3; // number of possible exceptions | |
| const char* exceptions[]{"NotJavaException","ILoveThisExceptionException","BeaversAteMyScissorsException"};// exception types | |
| const int penalty[]{10,20,50};// damage each exception does | |
| int playerhp = 100; // players are weaker than c++ | |
| int cplusplushp = 500; | |
| class PlayerWon{}; | |
| class CPlusPlusWon{}; | |
| void playerwins(){ | |
| if(cplusplushp<=0){ | |
| throw PlayerWon(); // end program with an exception - throw a class - why not? | |
| } | |
| } | |
| void computerwins(){ | |
| if(playerhp<=0){ | |
| throw CPlusPlusWon(); // end program with an exception - throw a class - why not? | |
| } | |
| } | |
| void player(int which){ | |
| cout<<"C++ sent you a:"<<endl; | |
| cout<<exceptions[which]<<endl<<endl; | |
| playerhp-=penalty[which]; | |
| computerwins(); | |
| throw cplusplus; // throw function pointer to cplusplus function -aka your turn | |
| } | |
| void cplusplus(int which){ | |
| cout<<"You sent c++ a:"<<endl; | |
| cout<<exceptions[which]<<endl<<endl; | |
| cplusplushp-=penalty[which]; | |
| playerwins(); | |
| throw player; // throw function pointer to player function -aka your turn | |
| } | |
| int main(){ | |
| void (*handle)(int)=cplusplus; // cplusplus plays first | |
| int seed =0; | |
| cout<<"Seed my random generator please!"<<endl; | |
| cin>>seed; | |
| rng.seed(seed); // seed the random generator | |
| while(1){ | |
| int exc; | |
| try{ | |
| exc = rng()%num; // randomly select an exception to be thrown | |
| handle(exc); // call function passing the random exception | |
| } | |
| catch(void (*a)(int)){ //catch a thrown function pointer | |
| handle=a; | |
| usleep(2000000); | |
| continue; | |
| } | |
| } | |
| return 0; | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment