问题
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