Noexcept equivilent in C#

Vas*_*sya 5 .net c# language-features exception

I want to ask is there in C# analogue for C++ "noexcept" attribute for methods which does not generate any exceptions. Something like that:

    public int SomeMethod() noexcept
    {
     throw new ArgumentNullException (); //Compile error: Method with 'noexcept' 
attribute can't generate exceptions.
    }
Run Code Online (Sandbox Code Playgroud)

And when I want to call this method in my code I need not to think about try/catch block for this method.

Sam*_*ade 4

据我所知,C# 中没有类似的东西(尽管我不是 100% 相信)。关于它的用途;当编写干净的代码时,您应该只在您期望异常发生的地方处理异常。这使得程序的流程和控制更加易于管理。

如果您不知道方法期间可能发生异常,或者发生您没有预料到的异常,那么您需要确定该异常是否被认为是关键的(因为它会导致应用程序失败);或者是否应该在代码中专门处理它。

  • 我希望更多的人明白“如果发生了你没有预料到的事情,崩溃可能是最好的做法”。如果您想避免这种情况,只需确保所有“空白”“try ... catch”语句仅出现在完全隔离的代码中,不与应用程序的其余部分共享状态。否则你就会面临非常奇怪的不一致错误。我已经调试过很多这样的应用程序,这是一个巨大的痛苦。 (2认同)