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
Probably to discourage overuse. A try-catch block is big and ugly, and you're going to notice when you're using it. This mirrors the effect that a catch has on your application's performance - catching an exception is extremely slow compared to a simple boolean test.
In general you should avoid errors, not handle them. In the example you give, a much more efficient method would be to use
if(!int.TryParse(s, out i))
i=0;
The simplest (I think) answer is that each block of code in C/C++/C# requires curly braces.
EDIT #1
In response to negative votes, directly from MSDN:
try-catch (C# Reference)
The try-catch statement consists of a try block followed by one or more catch clauses, which specify handlers for different exceptions.
As per definition says, it is a block, so it requires curly braces. That is why we cannot use it without { }
.
try // 1
try // 2
something();
catch { // A
}
catch { // B
}
catch { // C
}
does B catches try 1 or 2?
I don't think you can resolve this unambiguously, since the snippet might mean:
try // 1
{
try // 2
something();
catch { // A
}
}
catch { // B
}
catch { // C
}
try // 1
{
try // 2
something();
catch { // A
}
catch { // B
}
}
catch { // C
}
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.