I don't understand why the following code produces an error. Normally I can figure things out from the language specification, but in this case I don't understand the language specification.
This isn't causing problems in my code, by the way, I just want to understand the language.
Example:
bool success;
try
{
success = true;
}
catch
{
success = false;
}
finally
{
Console.WriteLine(success); // ERROR: Local variable 'success' might not be initialized before accessing
}
This behavior appears to be true of all versions of C#, but the quotes below are from C# Language Specification 5.0.
Section 5.3.3.14 Try-finally statements
The definite assignment state of v at the beginning of finally-block is the same as the definite assignment state of v at the beginning of stmt.
Here "beginning of stmt" refers to the beginning of the entire try-finally statement, i.e. just before try
.
Section 5.3.3.15 Try-catch-finally statements
The following example demonstrates how the different blocks of a try statement (§8.10) affect definite assignment.
static void F() {
int i, j;
try {
goto LABEL;
// neither i nor j definitely assigned
i = 1;
// i definitely assigned
}
catch {
// neither i nor j definitely assigned
i = 3;
// i definitely assigned
}
finally {
// neither i nor j definitely assigned
j = 5;
// j definitely assigned
}
// i and j definitely assigned
LABEL:;
// j definitely assigned
}
Can anyone explain why success
(in my example) or i
(in the language spec example) are not definitely assigned at the beginning of the finally-block?
The ' |= ' symbol is the bitwise OR assignment operator.
In mathematics, the tilde often represents approximation, especially when used in duplicate, and is sometimes called the "equivalency sign." In regular expressions, the tilde is used as an operator in pattern matching, and in C programming, it is used as a bitwise operator representing a unary negation (i.e., "bitwise ...
C operators are one of the features in C which has symbols that can be used to perform mathematical, relational, bitwise, conditional, or logical manipulations. The C programming language has a lot of built-in operators to perform various tasks as per the need of the program.
In C/C++, the # sign marks preprocessor directives. If you're not familiar with the preprocessor, it works as part of the compilation process, handling includes, macros, and more.
Simple reason is - There is no guarantee that the code in try
or catch
block will ever execute, before finally
block.
ThreadAbort
Exception can happen inside the try
block, but before assignment executes.
Runtime code executes after exception is thrown but before code in catch
blocks executes (Search for how exception handling works in .Net or "Structured Exception Handling").
Hence, code in try and catch block may never execute, before execution of finally
block.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With