How Am I Supposed to Access This Object?

closed account (zb0S216C)
The problem stems from try... catch(). I'm trying to handle any exceptions thrown from my class constructor. However, I cannot catch exceptions unless the test is performed in a try block. Of course, you already know this. First, my simple code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
struct Node
{
    static int IntentionalThrow()
    {
        throw("Allocation Failure");
    }

    Node()
    try
        : A(Node::IntentionalThrow())
    { }

    catch(const char *Error)
    {
        std::cout << Error;
    }

    private:
        int A;
};

int main()
{
    try
    {
        Node NewNode;
    }

    catch(const char *)
    {
        //...
    }
}

In the above code, I declared a Node instance. Since NewNode resides within a separate scope, it no longer exists once the try scope ends. So, how am I supposed to access NewNode after the test is performed? Any solutions to this? The exception handling within the class doesn't fix it.

Edit:

If an exception is thrown an caught within the class, is it safe to access the members?

Thanks :)

Wazzak
Last edited on
My first guess is that you shouldn't be trying to access NewNode anyway; since its constructor threw an exception, the object doesn't even exist.
closed account (zb0S216C)
Thanks for the prompt reply, Zhuge :)

This is my exact problem. Even if no exception is thrown, NewNode is still cut-off by scope. Accessing it proves troublesome.

Wazzak
Last edited on
If your constructor throws an exception, newNode never existed at all.

http://www.gotw.ca/gotw/066.htm
Last edited on
I think maybe your example isn't fully showing what kind of issue you're having. Why do you need to access an object you created inside the try block inside the catch block? The way I see exception handling here is that you are placing some code that could fail into the try block, and handling "exceptional" circumstances inside the catch. In other words, none of what is in the try block could be presumed to have worked, as it is all meant to be code that could fail "exceptionally".

So if NewNode needs to be accessed inside of the catch block, you need to sort of "guarantee" that it won't be the part of that code that will throw an exception, in which case you may as well move it outside of the try block. Do I make sense?
closed account (zb0S216C)
Zhuge wrote:
"Do I make sense?"

Yes, you do :) I'm going to bookmark this thread for future reference.

Brilliant! Thanks for the link, cire; it's answers my question.

Thanks again, Zhuge & cire :)

Wazzak
Last edited on
Topic archived. No new replies allowed.