views:

51

answers:

4

Hi!

Programming Java in Eclipse, I'm used to having to deal with exceptions. In C# with VisualStudio it seems I can not say "throws exception" on a method... After a lot of coding I found lots of exceptions, and had to catch them as I found them during testing. I'd like to be forced to handling them, so that VisualStudio can say that here you need a catch or I'm not going to let you go on :) Is this possible?

Thanks

+5  A: 

No. C# doesn't force you to handle exceptions. This was a concious design decision on the part of the language designers.

For details on why, see The Trouble With Checked Exceptions, where Anders Hejlsberg discusses why they aren't part of C#.

Reed Copsey
Oh well, too bad :) Thanks for the answer!
Johannes
Which, although allegedly error-prone, gives a programmer the freedom to state "I know what I am doing"
Armen Tsirunyan
@Johannes: Before you think of this as "bad", I'd read that interview. I used to think this was a flaw in C#, but I've completely converted to seeing this as a "pro"...
Reed Copsey
@Reed: Well I'm no pro, I could really need to know when some exception might throw! :)
Johannes
A: 

No, it's not possible.

What you can do is to look up the .NET library method you are executing in MSDN: the exceptions which are expected to be thrown by the method are documented there. Afterwards, you can decide which ones you want to catch and which ones you don't want to handle here.

Heinzi
No better way than to look them all up in documentation? There should be some possibility to do this in VisualStudio if you ask me :) Some type of "right-click -> exceptions that can explicit can be thrown" :)
Johannes
@Johannes: True, that would be nice, but since context-sensitive help in Visual Studio is quite good (just hit F1 while having the cursor over the method name), looking up documentation goes quite quickly.
Heinzi
A: 

You can use various tools to find the exceptions. There's also this thing for .NET 4 called Code Contracts that help you enforce pre/post conditions and possibly avoid some exceptions.

Greg
A: 

No there are no checked exceptions in C#. And the reasons are pretty simple:

1) they tend not to achieve there intended purpose because not every follows the recommended practice of either handling them explicitly or passing them up the chain. Instead what happens is that they are "eaten" by developers in the middle of the dev stack.
2) since they are naturally part of documentation rather than executable code, they should go into documentation and not clutter the code surface

3) C#/Framework documentation in dev tools are the ideal place for such documentation. Play around with the visual studio Object browser, browse to the method and you will see them mentioned in the lower pane.

mumtaz