.NET equivalent to Ruby begin / rescue / else

Ruby has an else block that will run / save (try / catch for .NET users)

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 were raised. Is there a constructor in .NET that provides this functionality?

+3


source to share


2 answers


In .NET, you can simply 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 inside will // some code

prevent the Execution Only section from appearing as it jumps to catch

, then finally

.

+3


source


There are things about exception handling that are possible in other languages, but not C #. One such example is a fault

handler
- in the IL, you can define a handler that will be triggered only when an error occurs.



fault

seems to be the opposite of what you want, but you can structure your logic so that some code only gets executed when an error occurs, no matter how you handle the exception..NET will generate a block try..fault

for the iterators. Bart De Smet once challenged his blog readers to try and mimic an error handler, you can read about it here .

+1


source







All Articles