CallMeNorm
CallMeNorm

Reputation: 2605

Thrown objects scope

I was wondering if thrown objects obey the same scope rules in c++ as everything else. Here is an example.

try{
  Error err;
  err.num = 10;
  err.str = "This will be thrown."
  throw err;
}
catch(Error e){
  cout << "Error num is: " << e.num << " error string is: " << e.str << endl;
}

Does that work or does the fact that err was created in the try block stop it from being used in the catch block?

Upvotes: 0

Views: 170

Answers (2)

Mike Seymour
Mike Seymour

Reputation: 254501

I was wondering if thrown objects obey the same scope rules in c++ as everything else.

The thrown object itself doesn't have a scope, since scopes only apply to names and it doesn't have a name. It has a slightly special lifetime: it is constructed somewhere by the throw statement, and then destroyed once the exception has been handled. In this case, the thrown object is a copy of err. Also, since you catch by value, the caught object e is a copy of the thrown object, not the object itself.

Does that work or does the fact that err was created in the try block stop it from being used in the catch block?

It "works" in that you can access e (a copy of err) in the catch block. You can't access err itself, since that has gone out of scope and been destroyed when the program left the try block; but the copy is still intact until you leave the catch block.

Upvotes: 5

paulsm4
paulsm4

Reputation: 121699

Yes, that works.

You throw "err", the catch block handles "e"; everything you initialized in "err" will be present in "e".

You can absolutely "catch" any exception you "throw" in your "try" block.

'Hope that helps.

Upvotes: 0

Related Questions