// throw.cpp #include #include //--- Virheluokat: ------------------------------------------------------ class cVirhe{ int err_n; string err_msg; public: cVirhe(int i=0,char *s=""):err_n(i),err_msg(s){}; int n() { return err_n; } const string &err() const { return err_msg; } }; class cNollallaJako: public cVirhe {}; class cNegatiivinen: public cVirhe { public: cNegatiivinen(int i=-1,char *s=""):cVirhe(i,s) {}; }; class cLiianIso: public cVirhe { public: cLiianIso(int i=10,char *s=""):cVirhe(i,s){} }; //--- Funktio, joka aiheuttaa virheen: ---------------------------------- double inv(int i) { if ( i < -1 ) throw cNegatiivinen(i,"ja pahasti"); if ( i < 0 ) throw cNegatiivinen(); if ( i == 0 ) throw cNollallaJako(); if ( i > 2 ) throw cLiianIso(i,"ja iso"); double x = 1.0/i; cout << "i = " << i << " x = " << x << "\n"; return x; } int laske(void) { for (int i=-2; i<4; i++) { try { double x; x = inv(i); (void)x; } catch ( cNollallaJako ) { cout << "Tulipa jaettua nollalla!\n"; } catch ( cNegatiivinen Neg) { cout << "Tulipa negatiivinen luku: " << Neg.n() << " " << Neg.err() << "\n"; } } cout << "Täällä ollaan onnellisesti!\n"; return 0; } int main(void) { try { laske(); } catch ( cVirhe Err ) { cout << "Tänne loput viat (" << Err.n() << "," << Err.err() << ")!\n"; } catch ( ... ) { cout << "Ja tänne sitten vielä jämät!\n"; } return 0; }