Just curious: Why is the syntax for try catch in C# (Java also?) hard coded for multiple statements? Why doesn\'t the language allow:
int i;
string s = DateT
The first think I can think of is that the curly braces create a block with its own variable scope.
Look at the following code
try
{
int foo = 2;
}
catch (Exception)
{
Console.WriteLine(foo); // The name 'foo' does not exist in the current context
}
foo
is not accessible in the catch block due to the variable scoping. I think this makes it easier to reason about whether an variable has been initialized before use or not.
Compare with this code
int foo;
try
{
foo = 2;
}
catch (Exception)
{
Console.WriteLine(foo); // Use of unassigned local variable 'foo'
}
here you can not guarantee that foo is initialized.