Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

.net

ruby

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?

like image 728
Dustin Davis Avatar asked Nov 25 '25 19:11

Dustin Davis


1 Answers

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.

like image 176
Reed Copsey Avatar answered Nov 28 '25 15:11

Reed Copsey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!