473,396 Members | 1,738 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Why does the try statement (and catch clause) require a block?

While the following is allowed:

if (a == b)
SomeFunction();
else
OtherFunction();

The following is not:

try
DoSomething();
catch (Exception e)
ProcessError(e);

I checked the C# grammar and it confirms that, unlike all other
compound statements, it requires a block - ie: the opening { and
closing } are required.
I just want to be able to write the following (to avoid too many
indents):

try
using (FileStream file = new FileStream("someFile.txt",
FileMode.OpenOrCreate))
using (SomeResource rsrc = new SomeResource())
{
// do stuff here
}
catch (Exception e)
{
// handle error here
}

Nov 26 '06 #1
12 1908
re****@gmail.com wrote:
While the following is allowed:

if (a == b)
SomeFunction();
else
OtherFunction();

The following is not:

try
DoSomething();
catch (Exception e)
ProcessError(e);
My best guess (and it IS just a guess) is that try blocks are not
free, and the language designers wanted them to stand out.

--

..NET 2.0 for Delphi Programmers
www.midnightbeach.com/.net
What you need to know.
Nov 26 '06 #2
Jon Shemitz wrote:
re****@gmail.com wrote:
>While the following is allowed:

if (a == b)
SomeFunction();
else
OtherFunction();

The following is not:

try
DoSomething();
catch (Exception e)
ProcessError(e);

My best guess (and it IS just a guess) is that try blocks are not
free, and the language designers wanted them to stand out.
In addition, both the try block and the catch block by necessity constitute
unique scopes - variables declared inside are not visible outside (nor would
they be if a single statement were allowed). For that reason, it makes
sense to require the braces to make it a formal block.

-cd
Nov 26 '06 #3
IMHO, I believe this is a combination of style and history. Style is
subjective and I don't take a side one way or the other as to whether it is
correct or not. However, one of the features of C# is that it is an
evolution of the C and C++ family of languages. Since the C++ try block has
curly braces, C# makes the migration path easier for the C++ programmer.
You'll find that C# syntax is similar in many ways to C++.

That said, I don't think there is a technical reason requiring that C# be
designed that way because VB.NET try blocks don't have begin/end, which is an
example of syntax that works without it.

Joe
--
http://www.csharp-station.com
"re****@gmail.com" wrote:
While the following is allowed:

if (a == b)
SomeFunction();
else
OtherFunction();

The following is not:

try
DoSomething();
catch (Exception e)
ProcessError(e);

I checked the C# grammar and it confirms that, unlike all other
compound statements, it requires a block - ie: the opening { and
closing } are required.
I just want to be able to write the following (to avoid too many
indents):

try
using (FileStream file = new FileStream("someFile.txt",
FileMode.OpenOrCreate))
using (SomeResource rsrc = new SomeResource())
{
// do stuff here
}
catch (Exception e)
{
// handle error here
}

Nov 26 '06 #4
Not correct Joe. Vb.Net does indeed require an 'End Try' for every
Try/Catch/Finally construct.

In addition, like C# variable can have block scope with a Try section, a
Catch section or a Finally section, which is why, in C#, 'blocking' is
required.
"Joe Mayo (C# MVP)" <Jo*********@discussions.microsoft.comwrote in message
news:61**********************************@microsof t.com...
IMHO, I believe this is a combination of style and history. Style is
subjective and I don't take a side one way or the other as to whether it
is
correct or not. However, one of the features of C# is that it is an
evolution of the C and C++ family of languages. Since the C++ try block
has
curly braces, C# makes the migration path easier for the C++ programmer.
You'll find that C# syntax is similar in many ways to C++.

That said, I don't think there is a technical reason requiring that C# be
designed that way because VB.NET try blocks don't have begin/end, which is
an
example of syntax that works without it.

Joe
--
http://www.csharp-station.com
"re****@gmail.com" wrote:
>While the following is allowed:

if (a == b)
SomeFunction();
else
OtherFunction();

The following is not:

try
DoSomething();
catch (Exception e)
ProcessError(e);

I checked the C# grammar and it confirms that, unlike all other
compound statements, it requires a block - ie: the opening { and
closing } are required.
I just want to be able to write the following (to avoid too many
indents):

try
using (FileStream file = new FileStream("someFile.txt",
FileMode.OpenOrCreate))
using (SomeResource rsrc = new SomeResource())
{
// do stuff here
}
catch (Exception e)
{
// handle error here
}


Nov 26 '06 #5
Stephany Young wrote:
In addition, like C# variable can have block scope with a Try section, a
Catch section or a Finally section, which is why, in C#, 'blocking' is
required.
A rather strong statement, that should probably have been qualified
with an "imho."

After all, a try statement doesn't *have* to have block-local
variables, and there wouldn't have been anything unusual in supporting
simple statements for try blocks but requiring compound statements if
you wanted block-local variables.

Similarly, while a `catch` statement *can* have a block local
exception variable, there wouldn't have been anything inconsistent
with making that local to the `catch` statement, whether that was
simple or compound. Look, for example, at `using` statements, `for`
loops, and `foreach` loops, each of which can declare a
statement-local variable (indeed, `foreach` loops *must* declare a
statement-local variable) while still taking both simple and compound
statements.

Iow, try statements are a C# inconsistency that can't really be
explained by invoking block locality.

--

..NET 2.0 for Delphi Programmers
www.midnightbeach.com/.net
What you need to know.
Nov 26 '06 #6
In that paragraph, the 2nd 'C#' should have read 'VB.NET'.
"Jon Shemitz" <jo*@midnightbeach.comwrote in message
news:45***************@midnightbeach.com...
Stephany Young wrote:
>In addition, like C# variable can have block scope with a Try section, a
Catch section or a Finally section, which is why, in C#, 'blocking' is
required.

A rather strong statement, that should probably have been qualified
with an "imho."

After all, a try statement doesn't *have* to have block-local
variables, and there wouldn't have been anything unusual in supporting
simple statements for try blocks but requiring compound statements if
you wanted block-local variables.

Similarly, while a `catch` statement *can* have a block local
exception variable, there wouldn't have been anything inconsistent
with making that local to the `catch` statement, whether that was
simple or compound. Look, for example, at `using` statements, `for`
loops, and `foreach` loops, each of which can declare a
statement-local variable (indeed, `foreach` loops *must* declare a
statement-local variable) while still taking both simple and compound
statements.

Iow, try statements are a C# inconsistency that can't really be
explained by invoking block locality.

--

.NET 2.0 for Delphi Programmers
www.midnightbeach.com/.net
What you need to know.

Nov 26 '06 #7
<re****@gmail.comwrote:
While the following is allowed:

if (a == b)
SomeFunction();
else
OtherFunction();

The following is not:

try
DoSomething();
catch (Exception e)
ProcessError(e);

I checked the C# grammar and it confirms that, unlike all other
compound statements, it requires a block - ie: the opening { and
closing } are required.
I just want to be able to write the following (to avoid too many
indents):
If you've got too much indentation, that suggests you should consider
refactoring. Taking out indentation will make your code harder to
understand.

Personally, I think it's more of a pity that your first example *does*
compile than that the second one doesn't.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 26 '06 #8
As seldom,

We agree. I don't like these legacy parts,

(as well not in VB.Net where it is the same before you think that it is
about C#).

:-)

Cor

"Jon Skeet [C# MVP]" <sk***@pobox.comschreef in bericht
news:MP***********************@msnews.microsoft.co m...
<re****@gmail.comwrote:
>While the following is allowed:

if (a == b)
SomeFunction();
else
OtherFunction();

The following is not:

try
DoSomething();
catch (Exception e)
ProcessError(e);

I checked the C# grammar and it confirms that, unlike all other
compound statements, it requires a block - ie: the opening { and
closing } are required.
I just want to be able to write the following (to avoid too many
indents):

If you've got too much indentation, that suggests you should consider
refactoring. Taking out indentation will make your code harder to
understand.

Personally, I think it's more of a pity that your first example *does*
compile than that the second one doesn't.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too

Nov 26 '06 #9
On Sat, 25 Nov 2006 20:36:25 -0800, "Carl Daniel [VC++ MVP]"
<cp*****************************@mvps.org.nospamwr ote:
>In addition, both the try block and the catch block by necessity constitute
unique scopes - variables declared inside are not visible outside (nor would
they be if a single statement were allowed). For that reason, it makes
sense to require the braces to make it a formal block.
You and Stephany Young have it backwards. A new nested scope is
defined by the braces, not by the keyword that comes before the
braces. There are plenty of C# keywords that are optionally followed
by braces -- if, else, catch, for, while -- and a new scope is opened
only if they are. It's the same in C and C++, by the way.
--
http://www.kynosarges.de
Nov 26 '06 #10
I found the answer to my own question here (from c#'s roots in c++):

http://groups.google.com/group/comp....a54d70f74b5093

To summarize:
--------------------------------------------
Suppose braces were not required:
try
try
foo();
catch(T t) { ... }
catch(U u) { ... }
....
A "catch" must be associated with some "try". In my example, I want
the second catch to be associated with the first try, as indicated
by the indentation. But since multiple catch blocks are allowed for
a try, the compiler would have to associate every catch with the
nearest try.
--------------------------------------------

The key here is that a try statement can have more than one catch
clauses. In contrast, each if statement only has one else clause.

Nov 26 '06 #11
re****@gmail.com wrote:
A "catch" must be associated with some "try". In my example, I want
the second catch to be associated with the first try, as indicated
by the indentation. But since multiple catch blocks are allowed for
a try, the compiler would have to associate every catch with the
nearest try.
Oh, duh! That makes perfect sense.

It doesn't explain why catch and finally blocks must have braces, but
I guess code like

try
{
This();
}
finally
That();

would seem really weird.

--

..NET 2.0 for Delphi Programmers
www.midnightbeach.com/.net
What you need to know.
Nov 26 '06 #12
Yep. If at first you don't succeed, try, try again.
:-)
--
Co-founder, Eggheadcafe.com developer portal:
http://www.eggheadcafe.com
UnBlog:
http://petesbloggerama.blogspot.com


"re****@gmail.com" wrote:
I found the answer to my own question here (from c#'s roots in c++):

http://groups.google.com/group/comp....a54d70f74b5093

To summarize:
--------------------------------------------
Suppose braces were not required:
try
try
foo();
catch(T t) { ... }
catch(U u) { ... }
....
A "catch" must be associated with some "try". In my example, I want
the second catch to be associated with the first try, as indicated
by the indentation. But since multiple catch blocks are allowed for
a try, the compiler would have to associate every catch with the
nearest try.
--------------------------------------------

The key here is that a try statement can have more than one catch
clauses. In contrast, each if statement only has one else clause.

Nov 26 '06 #13

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: John Bailo | last post by:
how come I can say: if() statement; else statement; but I cannot say try statment; catch() statement;
24
by: David Mathog | last post by:
If this: int i,sum; int *array; for(sum=0, i=0; i<len; i++){ sum += array; } is converted to this (never mind why for the moment):
6
by: cody | last post by:
Mostly always you use the using clause you deal with native ressources, so exception handlinjg is sooner or later inevitable. so why do we need to write try { using (File f =...
4
by: James Radke | last post by:
Hello, I am attempting to use the proper Try/Catch technique when accessing my Microsoft SQL server database and have a question... If I use something similar to the following: Try set up...
5
by: tni | last post by:
int x = 0; int y = 0; int z = 0; try { z = x / y; } catch (Exception) // THIS IS NOT A (DECLARATION)!!!! { }
11
by: cj | last post by:
Public Class MyStringLogger Private Shared m_loglock As New Object Public Shared Sub Write(ByVal str As String) SyncLock (m_loglock) Dim sw As New System.io.StreamWriter("c:\validate.log",...
4
by: garyusenet | last post by:
Hi I'm using the following code which is finally working. Public Class Form1 Shared ActElement As Object Shared ActFields As DataSet Public Sub SetActElement() Dim objApp As New Object
18
by: sunny | last post by:
Hi Why does C allows declaration of variable inside switch block. ex: foll prg does not gives "undeclared "b" error msg. but also does not initialize b to 20 int a=1; switch(a) { int b=20;...
12
by: lali.b97 | last post by:
Somewhere in a tutorial i read that if statement has performance overheads as code within the if statement cannot take benefit of pipeling of microprocessor and also that the compiler cannot...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.