Re: Question about exceptions.
LR wrote in message...
Is this code valid? And if so, what should the output be?
#include <iostream>
#include <exception>
int divide(const int a) {
std::cout << "1 divide(" << a << ")" << std::endl;
if(a == 0)
throw std::exception();
std::cout << "2 divide(" << a << ")" << std::endl;
return 1/a;
}
class X {
int k;
public:
X(const int a) try : k(divide(a)){
std::cout << "X(" << a << ")" << std::endl;
}
catch(const std::exception &) {
std::cout << "Caught by X(" << a << ")" << std::endl;
// throw; // add this (after first test run)
}
};
void test1() {
try {
X a(1);
X b(0);
}
catch(const std::exception &) {
std::cout << "Caught by test1" << std::endl;
// throw; // add this (after 2nd test run, for main() )
}
}
void test2() {
X a(1);
X b(0);
}
int main() {
test1();
test2();
}
TIA. LR
Going through it by hand (my TestBench is temp off-line (busy with another
project, different libraries) ).
// void test1() { try { X a(1); ....
1 divide(1)
2 divide(1)
X(1)
// .... X b(0);
1 divide(0)
Caught by X(0) // X b invalid
// void test2() { X a(1); .....
1 divide(1)
2 divide(1)
X(1)
// .... X b(0);
1 divide(0)
Caught by X(0) // X b invalid
If you want to see the "Caught by test1" message, you should re-throw in the
catch() in X Ctor (shown above).
**But I'm guessing.**
To be sure run the code with this main() as a safety net:
int main() try {
test1();
test2();
return 0;
} // main()
catch( std::exception const &) {
std::cout<< "main caught exception"<<std::endl;
return 1;
} // main()
catch( ... ) {
std::cout<<"caught unknown"<<std::endl;
return 1;
} // main()
See "Thinknog in C++" vol.2
"Part 1: Building Stable Systems, 1: Exception Handling, Function-level
try blocks" for more.
--
Bob R
POVrookie
Get "Thinking in C++", 2nd ed. Volume 1&2 by Bruce Eckel
(available for free here. You can buy it in hardcopy too.):
http://www.mindview.net/Books/TICPP/ThinkingInCPP2e.html