.NET equivalent of Ruby's begin/rescue/else

谁说我不能喝 提交于 2021-02-16 20:01:19

问题


Ruby has an else block that would go in a begin/rescue (try/catch for .NET folks)

begin
 #some code
rescue
 #oh noes! Catches errors like catch blocks in .NET
else
 #only executes when NO errors have occured
ensure
 #always executes - just like the finally in .NET
end

The code in the else block will only execute if no errors have been raised. Is there a construct in .NET that provides this functionality?


回答1:


In .NET, you can just list the code after #some code:

try
{
   // some code
   // Only executes when NO errors have occurred
}
catch (Exception e)
{
    // Catches errors
}
finally
{
    // Always executes
}

Any exception within // some code will prevent the "Only executes" section from occurring, as it will jump to the catch then finally.




回答2:


There are things with regards to exception handling that are possible in other languages, but not in C#. One such example is the fault handler - in IL it's possible to define a handler that will only fire if there was an error.

The fault seems to be the opposite of what you want, but you could structure the logic such that some code will only execute in case an error occurs, regardless of how you handled the exception. .NET will generate a try..fault block for iterators. Bart De Smet once challenged the readers of his blog to try and simulate fault handler, you can read more about it here.



来源:https://stackoverflow.com/questions/14904965/net-equivalent-of-rubys-begin-rescue-else

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!