C# Checked exceptions

后端 未结 3 1627
长情又很酷
长情又很酷 2021-01-07 05:47

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 Studi

相关标签:
3条回答
  • 2021-01-07 06:09

    To the question: "Is there any way to simulate (maybe via stylecop?) or turn on checked exceptions in Visual Studio?" - Yes: try this Visual Studio extension: https://marketplace.visualstudio.com/items?itemName=YoavFrandzel.CheckedExceptions

    0 讨论(0)
  • 2021-01-07 06:13

    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
    }
    
    0 讨论(0)
  • 2021-01-07 06:17

    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.

    0 讨论(0)
提交回复
热议问题