views:

182

answers:

3

One feature I really liked in Java that isn't in C# is checked exceptions. Is there any way to simulate (maybe via stylecop?) or turn on checked exceptions in Visual Studio?

Yes I know a lot of people dislike them, but I find they can be helpful.

+12  A: 

Far as I know, there's no way to do checked exceptions in C#. That feature (or a bug, depending on how you look at it :)) is not supported by the language.

Your best bet would be to add XML comments to your method, include the exceptions thrown by it and hope whoever calls your code reads the documentation.

Something like this:

/// <summary>
/// This is my method that does stuff.
/// </summary>
/// <exception cref="InvalidOperationException">This stuff can't be done!</exception>
public void DoStuff() 
{
    // do stuff
}
Anna Lear
+2  A: 

I bet you could use a tool like PostSharp to implement checked exceptions. Something like:

[Throws(typeof(MyExpection))]
public void Method()
{
   throw new MyException();
}

Not sure if something like this already exists in PostSharp or some other AOP framework (and the reasons why the designers of .NET don't like checked exceptions still hold true) but I bet it would be possible to do.

dkackman
A: 

There are some promising answers here Checked exception catching in C#

Allen