Does try catch share the same scoping block?

I have a try-catch sequence.

try 
{
    int tryCatchVar = 0
    ...other code...
}
catch
{
    if (tryCatchVar != 0) return;
}

I declared and assigned a variable in the try block. Normally a variable's scope is the block it was declared in as well as all blocks nested within it. However, because of the strong relational aspect of try-catch, I am wondering if the variable declared in try is in scope for catch?

If not, then I guess I would want to do the following:

int tryCatchVar

try
{
    tryCatchVar = 0
    ...other code...
}
catch
{
    if (tryCatchVar != 0) return;
}

Would that work?


Reasoning:

I have two parameters that may throw exceptions. However, due to the limitations of my application (which are immutable at this point) I can only log user error messages to one specific string. I'm thinking of implementing two try-catch sequences. If either/both are tripped, they would generate an internal log stored in tryCatch. Then, depending on the value of tryCatch I would generate a new error message.

Jon Skeet
people
quotationmark

However, because of the strong relational aspect of try-catch, I am wondering if the variable declared in try is in scope for catch?

You can test this easily for yourself, but the answer is no.

(Second part)

Would that work?

Again, you can test this easily for yourself, but the answer is no - because it won't be definitely assigned. You can fix it easily though:

int tryCatchVar = 0;

try
{
    ...other code...
}
catch
{
    if (tryCatchVar != 0) return;
}

(Of course I'd strongly recommend against catching all exceptions in this manner. Use targeted catch blocks, and it's very rarely a good idea to throw away the exception without at least logging it.)

people

See more on this question at Stackoverflow