try and catch help.

Can someone explain me why the output is 01?
I don't even understand how the compiler can run this without compilation error.
it is supposed to catch s, which from this code, I see none.... what am I doing wrong?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  #include <iostream>
    using namespace std;
    class X {
    public:
        X(void) { cout << 0; }
        ~X(void) { cout << 2; }
    };        
    
    int main(void) {
        try {
            X *x = new X();
        throw true;
            delete x;
        } catch(bool s) {
            cout << s;
        }
        return 0;
    }
Booleans are output as 0 or 1, if you want to see true or false you need to use std::boolalpha.
It catches whatever bool was thrown and calls it s. It's just like a function parameter; you can pass whatever named variable you want (or even, say, the literal value true) and the function just refers to it by the name it has in its formal parameter list.
What do you think is wrong with this code?

Line 13: This never gets called due to the throw. Therefore, memory leak.

-Albatross
wow I didn't know bool was either 0 or 1 (i.e true/ false)
so what I understand is that, on line 12*** throw true, outputs the "0"
and the line 14/15 outputs the 1, hence 01. am I right?
***my bad, line 11 that is.
Last edited on
On line 11 you call the constructor for X, which prints the 0. On line 12 you throw something, in this case a boolean value (True), which is caught at line 14. But you convert whatver is caught to a bool called s. Since you throw true, s is true as well. When you print it, it is 1. If on line 12 you throw false, it will print 00.
thank you so much for the supports, wow you guys are fast.
I keep failing my c++ assignments but you guys are giving me some hope
Topic archived. No new replies allowed.