try finally Error Handling without catch

  • Thread starter Thread starter A.M-SG
  • Start date Start date
A

A.M-SG

Hi,

I underestand that we can use try finally without catch clause. Something
like this:
try
{
throw new Exception("Test")
}
finally
{
// close all files
}

What exactly is this?


Thank you,
Alan
 
It ensures that when your code exits the try block, the code in the
finally is executed. You might use this for cleaning up external
resources (file handles etc.. )
 
A.M-SG said:
I underestand that we can use try finally without catch clause. Something
like this:
try
{
throw new Exception("Test")
}
finally
{
// close all files
}

What exactly is this?

It means that the finally block is executed whatever happens, but any
exceptions thrown in the try block are still propagated up the stack
(rather than being caught).
 
Hi,

I underestand that we can use try finally without catch clause. Something
like this:
try
{
throw new Exception("Test")
}
finally
{
// close all files
}

What exactly is this?


Thank you,
Alan
I am not quite sure what you are asking. THe finally clause
guarantees that the code inside it will be executed, no matter how the
try block terminates. This includes if the try block throws an
exception.

Try:

try {
Console.WriteLine("Alpha");
throw new Exception("Test");
Console.WriteLine("Beta");
}
finally {
Console.WriteLine("Gamma");
}

and see which bits show on screen.

rossum
 
If you are asking why you would use this, here is one snippet from my
code:

this._reactingToUser = true;
try
{
this.Model.PurchaseOrderNumber =
Convert.ToInt32(this._poNumber.Text);
... do more stuff to update the model ...
}
finally
{
this._reactingToUser = false;
}

This ensures that no matter what happens while I'm updating the model,
the _reactingToUser flag will always be set back to false at the end.

It's also handy for making sure that resources are released, as John
Murray pointed out, although there is the construct

using (...)
{
}

for that, too.
 
Back
Top